Freeware JavaScript Editor Perl Tutorials

↑

Main Page |

## Recipe 2.3 Comparing Floating-Point Numbers## 2.3.1 ProblemFloating-point arithmetic isn't exact. You want to compare two floating-point numbers and know whether they're equal when carried out to a certain number of decimal places. Most of the time, this is the way you should compare floating-point numbers for equality. ## 2.3.2 SolutionUse
# equal(NUM1, NUM2, PRECISION) : returns true if NUM1 and NUM2 are # equal to PRECISION number of decimal places sub equal { my ($A, $B, $dp) = @_; return sprintf("%.${dp}g", $A) eq sprintf("%.${dp}g", $B); } Alternatively, store the numbers as integers by assuming the decimal place. ## 2.3.3 DiscussionYou need the This problem is especially noticeable in a loop, where round-off error can silently accumulate. For example, you'd think that you could start a variable out at zero, add one-tenth to it ten times, and end up with one. Well, you can't, because a base-2 computer can't exactly represent one-tenth. For example: for ($num = $i = 0; $i < 10; $i++) { $num += 0.1 } if ($num != 1) { printf "Strange, $num is not 1; it's %.45f\n", $num; } prints out:
The !equal($num, 1, 5) then you'd have been okay.
If you have a fixed number of decimal
places, as with currency, you can often sidestep the problem by
storing your values as integers. Storing $wage = 536; # $5.36/hour $week = 40 * $wage; # $214.40 printf("One week's wage is: \$%.2f\n", $week/100); It rarely makes sense to compare more than 15 decimal places, because you probably only have that many digits of precision in your computer's hardware. ## 2.3.4 See AlsoThe |

Main Page |

↓

JavaScript Verifier Perl Tutorials

©