5 ms·
new Rational(2, 3) == new Rational(4, 6) You could implement Rationals to be structurally equal by simplifying them immediately on construction, but that may b
by mcbits 10y ago
new Rational(2, 3) == new Rational(4, 6)
You could implement Rationals to be structurally equal by simplifying them immediately on construction, but that may be a lot of unnecessary computation in some cases.
- jstimpfle 10y agoWith more context we could probably agree that it's not unnecessary computation if you want to do anything useful with the data.
- hota_mazi 10y agoIndeed. And you only have to do it once, you can then store the result (you should probably make that calculation lazily, though).
- jstimpfle 10y agoLazily or not, that would be a global design decision (use a lazy language or not)
- mcbits 10y agoIn a formula with multiple Rationals, it wouldn't always be necessary to simplify them before using them. You could just simplify the result if/when it's compared to another result. Also, the UI may need to display the unsimplified fraction. If you simplified them immediately, you'd have to store a factor somewhere to reconstruct the original (and not in the Rational class because that would ruin structural equality). In other words, "equal" for I/O purposes and "equal" for mathematical purposes could be different.
- jstimpfle 10y agoHow'd you compare the unsimplified number then? How would it be obvious at the calling site what happens? Better explicitly compare only the simplified part (again, structurally).
- mcbits 10y agoThe most straightforward way would be to simplify during the equivalence check and maybe cache the value. Or maybe there is some trick to compare them without simplifying. Point is that you can have a notion of "equal but not identical". No doubt it's also possible to represent rationals with only structural equality, but I'd have to see two competing implementations to judge which is more intuitive to use.
- dllthomas 10y ago> Or maybe there is some trick to compare them without simplifying. a / b == c / d is equivalent to a * d = c * b, although whether that's a good approach depends on a lot of things.
- smnplk 10y agoClojure supports rational type and it does simplify them. (def a (/ 1 2)) (def b (/ 8 16)) (= a b) true