Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl modulo operator question

Why does the first example print a wrong result ?

perl -le 'print $x = 100*1.15 % 5'
4
perl -le 'print $x = 1000*1.15 % 5'
0
like image 987
Eugene Yarmash Avatar asked Jul 26 '10 14:07

Eugene Yarmash


2 Answers

It's because of floating point arithmetic.

print $x = int(100*1.15);

Gives you 114.

like image 117
NullUserException Avatar answered Oct 14 '22 06:10

NullUserException


Rounding. Keep in mind that computers can't represent actual decimal places perfectly - they approximate. On my computer, perl -le 'print $x = (100*1.15)-115' gives the result -1.4210854715202e-14, which means that 100*1.15 is almost, but not quite, 115.

like image 27
Tassos Bassoukos Avatar answered Oct 14 '22 08:10

Tassos Bassoukos