Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I fix this Perl code so that 1.1 + 2.2 == 3.3?
    primarykey
    data
    text
    <p>How do I fix this code so that 1.1 + 2.2 == 3.3? What is actually happening here that's causing this behavior? I'm vaguely familiar with rounding problems and floating point math, but I thought that applied to division and multiplication only and would be visible in the output.</p> <pre><code>[me@unixbox1:~/perltests]&gt; cat testmathsimple.pl #!/usr/bin/perl use strict; use warnings; check_math(1, 2, 3); check_math(1.1, 2.2, 3.3); sub check_math { my $one = shift; my $two = shift; my $three = shift; if ($one + $two == $three) { print "$one + $two == $three\n"; } else { print "$one + $two != $three\n"; } } [me@unixbox1:~/perltests]&gt; perl testmathsimple.pl 1 + 2 == 3 1.1 + 2.2 != 3.3 </code></pre> <p>Edit:</p> <p>Most of the answers thus far are along the lines of "it's a floating point problem, duh" and are providing workarounds for it. I already suspect that to be the problem. How do I demonstrate it? How do I get Perl to output the long form of the variables? Storing the $one + $two computation in a temp variable and printing it doesn't demonstrate the problem.</p> <p>Edit:</p> <p>Using the sprintf technique demonstrated by aschepler, I'm now able to "see" the problem. Further, using bignum, as recommended by mscha and rafl, fixes the problem of the comparison not being equal. However, the sprintf output still indicates that the numbers aren't "correct". That's leaving a modicum of doubt about this solution.</p> <p>Is bignum a good way to resolve this? Are there any possible side effects of bignum that we should look out for when integrating this into a larger, existing, program?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload