civiltomain
civiltomain

Reputation: 1166

Cross-browser consistency in JavaScript floating point arithmetic

My goal is to have a centesimal degree/radians translation tool.

var PI      = 3.1415926535897936;
var PI_100  = 1.5707963267948968; // PI*0.5;
var PI_300  = 4.71238898038469;   // PI*(1.5);
var D_PI    = 6.283185307179587;  // 2*pi

var centTo  = 0.015707963267948967; 

Chrome evaluates the following expressions as shown:

PI*2 == D_PI      >>> true
PI*0.5 = PI_100   >>> true
PI*1.5 = PI_300   >>> true

100*centTo == PI_100  >>> true
300*centTo == PI_300  >>> true

Are these expressions always true on every browser?

Or must I use an epsilon when comparing?

var epsilon = 0.0000001;
Math.abs(a - b) < epsilon

Upvotes: 2

Views: 420

Answers (2)

IMSoP
IMSoP

Reputation: 97948

The ECMAScript standard defines a "number value" (there is technically no separate integer type) as "corresponding to a double-precision 64-bit binary form at IEEE 754 value". That should mean the behaviour is consistent across implementations, as they must at least emulate the exact precision of that format.

On the other hand, two different operations within the same implementation may produce different precision errors, so in general exact equalities are risky with any floating point implementation.

It would probably therefore be best to use an "epsilon" value, perhaps wrapping it in a library function called something like Utils.isSufficientlyEqualTo.

Upvotes: 3

aperl
aperl

Reputation: 144

No mater the programming language it is bad practice to use equivalency comparisons with floating point numbers, unless checking for infinity or NaN. It is always best to check and see if a value is within some tolerance.

Upvotes: 6

Related Questions