rawify / Fraction.js

Fraction is a rational numbers library written in JavaScript
https://raw.org/article/rational-numbers-in-javascript/
MIT License
465 stars 67 forks source link

What's the preferred way of comparing 2 Fractions? #80

Open bali182 opened 1 day ago

bali182 commented 1 day ago

I'm interested in what's the preferred way of comparing 2 fractionals. I see there is an equals method, but I'm interested in the >, <, >= and <= operators.

From what I can see looking at the API, this is the most straightforward way of doing this:

const a = new Fraction(1, 2)
const b = new Fraction(1, 2)

if (a.valueOf() > b.valueOf()) {
  // ...
}

Is this the preferred way to compare 2 Fractionals?

I see there is also this:

if (a.compare(b) < 0) {
  // ...
}

But this is not that great readability-wise.

infusion commented 1 day ago

I would avoid the valueOf() option, since Fraction.js uses BigInt if available internally beginning with v5. valueOf() however casts numerator and denominator to Number which only works as long as the numbers are in the interval of [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], so the preferred and safe way would be the compare() function. While I understand that it might be a bit confusing, I like to think of the "compare" statement as a minus sign, such as a-b <0, which is your wanted expression of a < b. Maybe that helps and sorry that I can't offer a more intuitive way since JavaScript doesn't allow a better syntax, like operator overloading

bali182 commented 1 day ago

Ah ok, thank you! I know library bloat can be annoying, but would something along the lines of

make sense? I don't know how common practice this is, but I've seen this type of method sets in languages that don't allow operator overloading (eg.: Java).

infusion commented 22 hours ago

@josdejong do you think this would be beneficial for math.js? Maybe also with your naming? "greater", "greaterEq", ...

josdejong commented 22 hours ago

To me, the short names like gt, gte, lt, and lte makes sense. The name that you choose does not make using it any harder or easier in mathjs. (I think the namings like greater and greaterEq are not very standard 😅 )

infusion commented 21 hours ago

Yea, I was asking more like do you think this would be useful for math.js ;)

josdejong commented 21 hours ago

ah ok. Right now the largerEq function of mathjs is implemented like (x, y) => (x.compare(y) !== -1) for fractions. So that could be replaced with (x, y) => x.gte(y), which is a bit more readable.