in reply to Re^7: Supporting long long types in XS (NV,PV)
in thread Supporting long long types in XS
The POSIX pod defines fmod as:
It returns the remainder $r = $x - $n*$y, where $n = trunc($x/$y). The $r has the same sign as $x and magnitude (absolute value) less than the magnitude of $y.
The weird thing is, the 'obvious' implementation of mod seems to work fine?
Perl> sub mod{ my( $a, $n ) = @_; return $a - $n * int( $a / $n ); };; Perl> print mod( 4.5, 1.25 );; ## prints 0.75 Perl> print mod( 4.5, -1.25 );; ## prints 0.75 Perl> print mod( -4.5, -1.25 );; ## prints -0.75 Perl> print mod( -4.5, 1.25 );; ## prints -0.75
Which compares favourably with the results of my C compilers view of the world:
Perl> use POSIX qw[ fmod ];; Perl> print fmod( 4.5, 1.25 );; ## prints 0.75 Perl> print fmod( 4.5, -1.25 );; ## prints 0.75 Perl> print fmod( -4.5, 1.25 );; ## prints -0.75 Perl> print fmod( -4.5, 1.25 );; ## prints -0.75
I'm not sure how ruby arrives at it's take on the subject? Uses abs on the arguements, divides, truncates and multiplies, then sets the sign of the results according to the divisor?
c:\test>\ruby\bin\ruby -e"p 4.5 % 1.25" ## prints 0.75 c:\test>\ruby\bin\ruby -e"p 4.5 % -1.25" ## prints -0.5 c:\test>\ruby\bin\ruby -e"p -4.5 % 1.25" ## prints 0.5 c:\test>\ruby\bin\ruby -e"p -4.5 % -1.25" ## prints -0.75
That still makes more sense than the current perl implementation.
|
|---|