type frac struct {
integer, numerator, denominator int
}
The typical implementation in other languages calls this a rational, and does type frac struct {
numerator, denominator int
}
That makes the code easier. Is there a reason for keeping the integer part around?Also, for FloatToFrac, you may want to look into continued fractions. They make it extremely easy to find better and better rational approximations to any number (https://en.wikipedia.org/wiki/Continued_fraction#Best_ration...)
This example also reminds me of why golang won’t soon become my favorite language. It’s just not expressive enough for this kind of stuff. If you’re using rationals, you really want to be able to write
rational r = 3/4
print(r * r + 2/13)
and get 149/208 as output.I'm guessing accuracy. This way, the numerator and denominator have more range to represent just the fractional part.
Thinking more about this, I think most implementations of rational use some bigint type for both numerator and denominator, completely solving that issue.
That isn’t performant, but I can’t think of code that needs rationals that doesn’t need exactness, and if you don’t need exactness, floating point will do fine.
The heading should be: "Finally a Golang library that retrofits Golang with a fractions datatype." -- relating only to Golang, instead of creating the wrong impression, that this is anything new in programming.
> Go provides rational numbers in the standard library, in the math/big package (https://pkg.go.dev/math/big#Rat)
Equating these two is just an approximation ... and based on the example, one that was carried out without any obvious accuracy requirement.
So why not 1 65/97 which is more accurate or 1 67/100 which is perfectly accurate?
Messing around with fractions is still only an approximation at best so it's hard to see how this really buys you much of anything except lost efficiency. Why not just use floats and format as a fraction for display/output if this is what "floats" your boat?