Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Floating point numbers in Javascript

Floating point numbers in Javascript

Initiate developers to the particularity of the floating point numbers implementation in javascript.

Avatar for Pierre Dulac

Pierre Dulac

May 30, 2014

Other Decks in Technology

Transcript

  1. Experiments $ node ! > 0.1 + 0.2 == 0.3

    false ! > 0.1 + 0.2 == 0.30000000000000004 true ! > Math.pow(2, 1023) 8.98846567431158e+307 ! > Math.pow(2, 1024) Infinity ! > +Infinity + Infinity Infinity ! > -Infinity + Infinity NaN
  2. Decimal representation • The every day used representation • The

    only one our brain can calculate in a = d[n]*10^n + d[n-1]*10^(n-1) + ... + d[0]*10^0 + ... + d[-p]*10^(-p)
  3. Scientific Notation We’ve all seen numbers formatted like ! 6.02214129

    * 10^23 Usually used in Physics. And this is the closest to the floating point representation we can get !
  4. Floating point representation • Replicate the scientific notation • Use

    a binary format (for efficiency) • Maximize precision
  5. IEEE 754 The representation of floating points in JavaScript follows

    the format as specified in IEEE-754. 6.02214129 * 10^23
  6. IEEE 754 The representation of floating points in JavaScript follows

    the format as specified in IEEE-754. 6.02214129 * 10^23 • Sign on the first bit • Exponent encoded on 11 bits
 25 is the exponent in the exemple,
 because 2^78 < 6.022 * 10^23 < 2^79 • Significand encoded on 52 bits
 02214129 is the significand
  7. IEEE 754 The representation of floating points in JavaScript follows

    the format as specified in IEEE-754. 6.02214129 * 10^23 • Sign on the first bit • Exponent encoded on 11 bits
 25 is the exponent in the exemple,
 because 2^78 < 6.022 * 10^23 < 2^79 • Significand encoded on 52 bits
 02214129 is the significand
  8. Unit of Last Precision Number.prototype.exponent = function(){ return Math.floor(Math.log(this)/Math.log(2)); };

    ! Number.prototype.bias = function() { return 1023; }; ! Number.prototype.biasExponent = function(){ return this.exponent() + this.bias(); }; ! Number.prototype.ulp = function(){ return Math.pow(2, this.biasExponent() - this.bias() - 52); }; Extends `Number` to compute the ULP.