Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add math.IsNearlyZero() and math.IsNearlyEqual() #2172

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

xCynDev
Copy link

@xCynDev xCynDev commented Dec 12, 2024

These simple functions should be used when comparing numbers instead of ==, since floating point precision issues easily arise.
Felt like making them since someone on the Garry's Mod Discord server was confused as to why the following didn't work:

image

So now, you can use math.IsNearlyEqual() or math.IsNearlyZero() which solves the issue:

image

The functions allow you to give them a tolerance of your choice, but they'll default to math.exp( -8 ) otherwise.

Additional reason why the function is needed:

image

It's more visible when you display the decimal values.

@CornerPin
Copy link
Contributor

  • I think math.IsNearlyEqual should be renamed to math.IsEqualTol for consistency because we already have methods like Angle:IsEqualTol and Vector:IsEqualTol. Similarly, math.IsNearlyZero can be renamed to math.IsEqualZeroTol.
  • An epsilon of $e^{-8}$ seems arbitrary to me, did you mean to set it to 1e-8 instead?

@xCynDev
Copy link
Author

xCynDev commented Dec 12, 2024

  • I think math.IsNearlyEqual should be renamed to math.IsEqualTol for consistency because we already have methods like Angle:IsEqualTol and Vector:IsEqualTol. Similarly, math.IsNearlyZero can be renamed to math.IsEqualZeroTol.

Wouldn't be against it. In my opinion, IsNearlyEqual is more readable than IsEqualTol, I would keep it that way if it isn't going to prevent it from being merged as it won't affect new or old code.

Especially since IsEqualTol() looks like IsEqualTo() at a glance and could be confusing.

  • An epsilon of $e^{-8}$ seems arbitrary to me, did you mean to set it to 1e-8 instead?

Yep! TIL Lua supports 1e-8 as a constant, I'll fix that in a bit.

@robotboy655
Copy link
Collaborator

Fixes Facepunch/garrysmod-requests#1991

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants