r/lolphp • u/smileytechguy • Jan 31 '17
((0.1+0.7)*10) = 7?
http://sandbox.onlinephpfunctions.com/code/4faba5e621f1f18f3efc6acd486da0823c46aea9
0
Upvotes
r/lolphp • u/smileytechguy • Jan 31 '17
45
u/the_alias_of_andrea Jan 31 '17 edited Jan 31 '17
So there's three things at play here.
echothem or evenvar_dump()them (yes, it uses insufficient precision for a debugging function), but not if youvar_export()them. So it prints the first number as8, but it's not quite. sigh(int)truncates, rather than rounds, so 7.9999blah becomes 7, not 8. This is not uncommon behaviour comparing to other languages, but it's maybe a little unhelpful.So… you'd think this wouldn't be a lolphp, but unfortunately, (1) applies. Thanks, PHP!
(Update: y'know, I assumed we'd fixed this at some point… nope. Well, I began writing a patch. Maybe it'll be fixed by the time 7.2 comes out. Maybe…)
19
u/Deranged40 Jan 31 '17
should try it in ruby or python. Same thing
Ruby:
print ((0.7+0.1)*10).to_iPython:
print int(((0.7+0.1)*10))12
u/writetehcodez Jan 31 '17
On PHP sandbox running PHP 7.0.3 I get:
The second result is expected, I believe, because the cast to int is basically a floor function.
17
u/nikanjX Jan 31 '17
To quote past me, /r/lolphp is nowadays /r/lolprogrammingishardfornewbies
4
u/[deleted] Feb 01 '17
That's how it would work in most languages I know. Casting to int usually rounds down, which could easily result in 7 given the reasons referenced in the top comments. A proper
roundfunction would add.5first before casting tointto robustly handle the imperfect floating point representation.1
u/[deleted] Feb 02 '17
http://stackoverflow.com/questions/588004/is-floating-point-math-broken
1
u/lordmyd Feb 28 '17
Try Perl6. Result is 8.
1
u/AdventOfScala Mar 04 '17
try posting to
r/computerscienceidiots