HollyKing has asked for the wisdom of the Perl Monks concerning the following question:
Greetings!
I have a need to control the rounding direction being used for floating point calculations. In C I would just call fegetround() and fesetround(). I have used Inline::C with some success, but I wonder if there isn't a better way to accomplish the same thing.
Is there some magic flag or module that will let me manipulate the rounding mode? I think my options are:
I've included a small program below that shows my current solution. This works with Strawberry Perl although I have yet to test it anywhere else so YMMV.
#!/usr/bin/perl use warnings; use strict; use Inline C => <<'END_C'; #include <fenv.h> int _getround() { return fegetround(); } int _setround(int mode) { return fesetround(mode); } int _round_down() { return fesetround(FE_DOWNWARD); } END_C ## simulate my object my $one = 1.0; my $three = 3.0; ## save the rounding mode and set to round towards negative infinity my $mode = _getround(); my $changed = _round_down(); ## perform the calculations my $lb = $one / $three; my $ub = -( -$one / $three ); ## restore the original rounding mode to be nice _setround($mode); ## display the results printf( "\$lb = %.23f\n", $lb ); printf( "\$ub = %.23f\n", $ub ); print "\$lb == \$ub ", $lb == $ub ? 'true' : 'false', "\n"; print "\$changed = $changed\n";
P:\>fround $mode = 0 $lb = 0.33333333333333331000000 $ub = 0.33333333333333337000000 $lb == $ub false $changed = 0
Owl looked at him, and wondered whether to push him off the tree; but, feeling that he could always do it afterwards, he tried once more to find out what they were talking about.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Is there a better way to call fe(get|set)round?
by toolic (Bishop) on Jun 30, 2007 at 02:20 UTC | |
by HollyKing (Pilgrim) on Jul 04, 2007 at 18:38 UTC | |
Re: Is there a better way to call fe(get|set)round?
by bart (Canon) on Jun 30, 2007 at 22:28 UTC | |
by HollyKing (Pilgrim) on Jul 04, 2007 at 18:44 UTC | |
Re: Is there a better way to call fe(get|set)round?
by Moron (Curate) on Jul 02, 2007 at 12:52 UTC | |
by BrowserUk (Patriarch) on Jul 02, 2007 at 13:26 UTC | |
by HollyKing (Pilgrim) on Jul 04, 2007 at 18:56 UTC |