php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #43624 fmod($a,$b) wrong when $b is a multiple of $a - continued
Submitted: 2007-12-18 14:36 UTC Modified: 2007-12-22 17:21 UTC
From: csaba at alum dot mit dot edu Assigned:
Status: Not a bug Package: Math related
PHP Version: 5.2.5 OS: Win XP
Private report: No CVE-ID: None
 [2007-12-18 14:36 UTC] csaba at alum dot mit dot edu
Description:
------------
This continues bug report 43572 at http://bugs.php.net/bug.php?id=43572&edit=2
which discussion is incomplete, yet has been prematurely closed.

> The value that you expect (0) is obtained using float precision.
> (In C) PHP uses double, and with this type fmod() returns 1.3.

So, to be concrete:
$a = 6.5;  print gettype($a);  // double
$b = 1.3;  print gettype($b);  // double
$c = $a / $b; print gettype($c);  // double

$d = 5.0;  print gettype ($d);  // double
print $c - $d;                  // 0
print (gettype($c - $d));       // double
print ($c===$d) ? "same" : "different";  // same

print gettype ($b - fmod($a, $b));  // double
print $b - fmod($a, $b);  // 2.22044604925E-16


In other words, PHP's own (double) math shows that 6.5 / 1.3 === 5.0
Regardless of the internal representation and precision of 6.5 and 1.3, division of the former ($a) by the latter ($b) results in a double value identical to 5.0.
fMod should return 0 in this situation.

Csaba Gabor from New York
PS.  I would prefer that these comments be moved to bug 43572 and that it be reopened until the discussion is completed, rather than having multiple threads.


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-12-18 15:41 UTC] felipe@php.net
C code:
---
float a = 6.5, b = 1.3;
double c = 6.5, d = 1.3;

puts("Float:");
printf("%f\n", fmod(a, b));
printf("%f\n", a / b);
printf("%f\n", b - fmod(a, b)); 

puts("Double:");
printf("%G\n", fmod(c, d));
printf("%G\n", c / d);
printf("%G\n", d - fmod(c, d));
---
Result:

Float:
0.000000
5.000000
1.300000
Double:
1.3
5
2.22045E-16

 [2007-12-22 17:21 UTC] jani@php.net
Discuss using mails. This is not a discussion forum!
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed May 08 04:01:31 2024 UTC