Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: float values and operators

by ikegami (Patriarch)
on Aug 11, 2004 at 21:21 UTC ( [id://382098]=note: print w/replies, xml ) Need Help??


in reply to float values and operators

Here's how to get around the problem:

sub TOLERANCE () { 1e-13 } sub are_equal { my ($a, $b) = @_; return (abs($a-$b) < TOLERANCE); } print('==: ', (36.8 == 36.6+0.2) ?'equal':'unequal', "\n +"); print('are_equal: ', are_equal(36.8, 36.6+0.2) ?'equal':'unequal', "\n +"); __END__ output ====== ==: unequal are_equal: equal

Replies are listed 'Best First'.
Re^2: float values and operators
by ikegami (Patriarch) on Aug 11, 2004 at 21:41 UTC

    I went nuts and here's a more general compare function (works like <=>)

    sub TOLERANCE () { 1e-13 } sub compare { my ($a, $b, $tol) = @_; $tol = TOLERANCE unless (defined($tol)); my $diff = ($a - $b); if ($diff > +$tol) { return +1; } if ($diff < -$tol) { return -1; } return 0; } sub format_cmp { my ($cmp) = @_; if ($cmp < 0) {return "<"; } if ($cmp == 0) {return "="; } if ($cmp > 0) {return ">"; } } print('35 <=> 36 = ', format_cmp(35 <=> 36 ), ' ', f +ormat_cmp(compare(35, 36 )), ' = compare(35, 36 )', "\ +n"); print('35 <=> 35 = ', format_cmp(35 <=> 35 ), ' ', f +ormat_cmp(compare(35, 35 )), ' = compare(35, 35 )', "\ +n"); print('36 <=> 35 = ', format_cmp(36 <=> 35 ), ' ', f +ormat_cmp(compare(36, 35 )), ' = compare(36, 35 )', "\ +n"); print('36.8 <=> 36.6+0.2 = ', format_cmp(36.8 <=> 36.6+0.2), ' ', f +ormat_cmp(compare(36.8, 36.6+0.2)), ' = compare(36.8, 36.6+0.2)', "\ +n"); __END__ output ====== 35 <=> 36 = < < = compare(35, 36 ) 35 <=> 35 = = = = compare(35, 35 ) 36 <=> 35 = > > = compare(36, 35 ) 36.8 <=> 36.6+0.2 = < = = compare(36.8, 36.6+0.2)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://382098]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2024-04-25 17:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found