Skip to content

Instantly share code, notes, and snippets.

@neclimdul
Last active July 18, 2017 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neclimdul/79d887d655ee5cec4bec50faa94c4382 to your computer and use it in GitHub Desktop.
Save neclimdul/79d887d655ee5cec4bec50faa94c4382 to your computer and use it in GitHub Desktop.
Testing float behavior in a couple languages. https://bugs.php.net/bug.php?id=74925
$ cat test.php
<?php
// Extra output to show how php displays things different.
var_dump(54.83 + 0.01);
printf("%.18e\n", 54.83 + 0.01);
var_dump(54.83 + 0.01 == 54.84);
var_dump(3 * 202.3);
printf("%.18e\n", (3 * 202.3));
var_dump((3 * 202.3) == 606.9);
for($v = -1; $v < 0; $v += 0.2){
printf("%.18e\n", $v);
var_dump($v);
}
$ php test.php
float(54.84)
5.483999999999999631e+1
bool(false)
float(606.9)
6.069000000000000909e+2
bool(false)
-1.000000000000000000e+0
int(-1)
-8.000000000000000444e-1
float(-0.8)
-6.000000000000000888e-1
float(-0.6)
-4.000000000000000777e-1
float(-0.4)
-2.000000000000000666e-1
float(-0.2)
-5.551115123125782702e-17
float(-5.5511151231258E-17)
$ cat test.js
console.log(54.83 + 0.01);
console.log(54.83 + 0.01 == 54.84);
console.log(3 * 202.3);
console.log((3 * 202.3) == 606.9);
$v = -1
while ($v < 0) {
console.log($v);
$v += 0.2;
}
$ node test.js
54.839999999999996
false
606.9000000000001
false
-1
-0.8
-0.6000000000000001
-0.4000000000000001
-0.20000000000000007
-5.551115123125783e-17
$ cat test.rb
puts 54.83 + 0.01
puts 54.83 + 0.01 == 54.84
puts (3 * 202.3)
puts (3 * 202.3) == 606.9
$v = -1
while $v < 0 do
puts $v
$v += 0.2
end
$ ruby test.rb
54.839999999999996
false
606.9000000000001
false
-1
-0.8
-0.6000000000000001
-0.4000000000000001
-0.20000000000000007
-5.551115123125783e-17
$ cat test.c
#include<stdio.h>
int main() {
printf("%e\n", 54.83 + 0.01);
printf("%s\n", 54.83 + 0.01 == 54.84 ? "true" : "false");
printf("%e\n", 3 * 202.3);
printf("%s\n", (3 * 202.3) == 606.9 ? "true" : "false");
for (double v = -1; v < 0; v += 0.2) {
printf("%e\n", v);
}
return 0;
}
$ gcc test.c && ./a.out
5.484000e+01
false
6.069000e+02
false
-1.000000e+00
-8.000000e-01
-6.000000e-01
-4.000000e-01
-2.000000e-01
-5.551115e-17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment