fraction icon indicating copy to clipboard operation
fraction copied to clipboard

Add From for f64 and f32

Open feefladder opened this issue 1 year ago • 6 comments

It would be nice to have api for directly converting to floats, since conversion cannot fail (as far as I know)

feefladder avatar Jan 05 '24 06:01 feefladder

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));.

dnsl48 avatar Jan 05 '24 07:01 dnsl48

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 :)

feefladder avatar Jan 07 '24 21:01 feefladder

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.

dnsl48 avatar Jan 08 '24 19:01 dnsl48

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. 😄

onkoe avatar Apr 04 '24 14:04 onkoe

Hi @onkoe, Sure, PRs are welcome. Otherwise, we may include that into the next version.

dnsl48 avatar Apr 05 '24 06:04 dnsl48

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 :)

feefladder avatar Apr 22 '24 16:04 feefladder