Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re^2: [OT: JavaScript] JS remainder operation ('%')

by syphilis (Archbishop)
on Jan 17, 2024 at 12:39 UTC ( [id://11157042]=note: print w/replies, xml ) Need Help??


in reply to Re: [OT: JavaScript] JS remainder operation ('%')
in thread [OT: JavaScript] JS remainder operation ('%')

Up to now it was my understanding that the "remainder" operation is defined for integer operands only.

That sounds sane to me - but why would these online calculators then provide a value for the remainder when one or both inputs is non-integer ?
Surely, the sane thing to do would be to throw an exception.

With Floats, you have to deal with rounding errors

That's not really a problem if you're prepared to apply (and adhere to) consistent rounding practice.
Sure, that practice doesn't avoid rounding, but it does mean that there's only one correct result.
Also, for the particular example I've given, the difference between the 2 results (0x1.99a24dd70e56p+29 versus 0x1.99a24dd7p+29) appears to be more than a rounding discrepancy.
(To my eyes, it looks more like a precision discrepancy.)

Sorry- it might seem that I'm "taking you to task" over your response, and that's not my intention.
I'm quite happy to accept that it's silly to be thinking about this, but I just wanted to present those counter-arguments in case they have some validity.

Thanks for the reply.

Cheers,
Rob

Replies are listed 'Best First'.
Re^3: [OT: JavaScript] JS remainder operation ('%') (modulo with non-integers)
by LanX (Saint) on Jan 17, 2024 at 13:24 UTC
    Strictly speaking is Modulo only defined for positive integers, excluding 0 for the dividend.

    Many languages take incompatible liberties in extending this definition by relying on the same implementation/algorithm, but also allowing floats as input.

    The rounding errors theory in your case is very convincing. But you should also check results with negative values and error cases

    > Surely, the sane thing to do would be to throw an exception.

    NB: JS is particularly reluctant to throw exceptions, it rather follows the "quiet" NaN (= not a number) approach, to silently fail.

    IMHO it's impossible to translate this behavior to efficient pure Perl.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    see Wikisyntax for the Monastery

    Update

    I have problems imagining a use case for float modulo operations, except reimplementing division.

    Any ideas?

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (10)
As of 2024-05-21 10:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found