fraction
fraction copied to clipboard
Add From for f64 and f32
It would be nice to have api for directly converting to floats, since conversion cannot fail (as far as I know)
Hi @feefladder,
Thanks for raising this.
Unfortunately, straight conversion into floats cannot be guaranteed without precision loss.
E.g. 1/3
cannot be represented as a decimal without data loss.
The simplest lossy way to convert would be to manually divide f64::from(.numer()) / f64::from(.denom())
.
A more controlled way could be via f64::from_str(format!("...", fraction));
.
The conversion would also need a match statement for ±infty and Nan.
I would argue that floats are lossy by definition and converting the conceptual value of a fraction to a float means acceptig lossy conversions/operations; From the perspective of the fraction it is lossy, but from the perspective of the float it is lossless: f64::from(1/3) gives the best possible float representation. Aka 1f64/3f64 === f64::from(1/3)
. Compare that to f32::from(f64)
not being implemented because f64 could overflow f32 (and precision loss).
Maybe as a feature called lossy-float-from
? The main difference with floats and other types is that conversion cannot fail.
Okok. Just realized that bigint frac could overflow f64, but thats not the type I'm asking here :)
I agree, there could be specific lossy features that make a a lot of sense and would help :)
We already have the approx
module. Probably could add more approximate conversions in there.
Hey there! I know beggars can't be choosers, but I find this crate to be way less useful without this kind of abstraction. It doesn't feel good to spin this yourself - reminds me of C... 😭
In my view, there should at least be a feature-flag'd submodule with as_f32_lossy()
and as_f64_lossy()
methods for these types.
Are there any implementation barriers you see for this kind of thing? If someone were to implement it, what would you want to see? And would you accept a PR?
Thanks for the useful crate! I hope to see it continue to improve. 😄
Hi @onkoe, Sure, PRs are welcome. Otherwise, we may include that into the next version.
Yeah @onkoe should be not that much of an effort (for you :P)! There's already macros in the crate for try_into
and @dnsl48 is quite supportive for getting stuff merged :)