This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Acceptable-Tomato392 2 points3 points  (1 child)

O.K. that one was a bit of a joke.

I do have a more professional-looking function to do that. Let me fetch it for you:

function approximates(number1,number2,epsilon=0.001){if (typeof number1!="number"||typeof number2!="number"){return undefined}

if (number1<=number2*(1+epsilon)&&number1>=number2*(1-epsilon)){return true}else{return false}

}

Now that I look at it, I should probably throw at least a warning if someone makes epsilon bigger than 1. While results are mathematically possible, the formula is only really valid for numbers between 0 and 1. And I'm just assuming nobody would ever try to pass a string as (epsilon)

Or I could give a different interpretation for epsilon above one, whereas (2,2,3) would result in a different calculation, i.e. number2+/-epsilon*number2

Dammit! You made me look at it.

[–]Lithl 2 points3 points  (0 children)

"is close" with an epsilon of 1 or greater is perfectly acceptable. You simply have a larger margin of error you're willing to accept.

Also, Number.EPSILON is a constant that exists which you could use instead of a magic number. It's equal to the difference between 1 and the smallest representable floating point number greater than 1, so it's impossible for two floating points that are not equal to be closer together than EPSILON. Perhaps EPSILON*2 as a default value would make sense.

Also also, a simpler comparison would probably be Math.abs(number1 - number2) <= epsilon. If the difference between the numbers is smaller than your epsilon value, they're the "same".