Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 222
civiltomain Avatar asked May 31 '26 14:05

civiltomain


1 Answers

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.

like image 59
aperl Avatar answered Jun 04 '26 12:06

aperl