Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP actually use IEEE-754 floating point numbers?

The IEEE-754 floating point standard says:

Four mutually exclusive relations are possible: less than, equal, greater than, and unordered. The last case arises when at least one operand is NaN. Every NaN shall compare unordered with everything, including itself.

And yet (codepad here):

<?php

echo phpversion() . " " . zend_version() . " " . php_uname() . "\n";
// 5.2.5 2.2.0 Linux 2cf38fbc9b9e 3.11.0-15-generic #25-Ubuntu SMP
// Thu Jan 30 17:22:01 UTC 2014 x86_64

NAN < NAN; // true
NAN > NAN; // true
INF < INF; // true
INF > INF; // true

So clearly there is more than one relation between NAN and NAN (and between INF and INF), when there should only be one. In many (most? all?) languages with IEEE-754 floats 'unordered' means that NaN < NaN is false, and NaN > NaN is false, and NaN == NaN is false. Does this demonstrate that PHP does not use IEEE-754 floating point numbers?

like image 433
tomjakubowski Avatar asked May 28 '14 02:05

tomjakubowski


1 Answers

It is useful to separate two ideas:

  1. Floating point number format
  2. Language rules for how numbers behave.

Language standards bodies can specify, or leave unspecified, as much or as little of the IEEE floating point behavior as they think fit. You cannot tell from how the NaN comparisons behave whether or not an IEEE floating point format is being used.

For example, Java specifies behavior for float and double that would be very difficult to implement without using the IEEE 754 32 bit and 64 bit binary formats. On the other hand, Float and Double both have comparison methods that consider a NaN to be equal to itself and greater than all other floating point numbers.

According to the PHP Language Reference Floating point numbers "Although it depends on the system, PHP typically uses the IEEE 754 double precision format..."

like image 56
Patricia Shanahan Avatar answered Oct 15 '22 09:10

Patricia Shanahan