Is there a thing like a flexible number data type?

I'm writing a calculator, and currently implementing factorial functionality. The calculator uses f64 as the primary data type, because decimals are pretty crucial to calculators, but this is incompatible with factorials for two reasons:

  1. You can't calculate the factorial of a float.
  2. f64 is unlikely to be able to hold larger factorials.

For this reason, I want to use an i128 for factorials, and factorials only. Of course, it is difficult to switch between floats and integers while maintaining precision, so I wanted to ask if there was a way/crate with a data type that can flex between an integer and a float, or simplifies conversion between the two while maintaining precision.

Alternatively are there crates that allow much larger floating types, so I can simply store an integer as a float for these calculations?

A quick search of finds astro_float, which looks like it fits the bill. I don’t have any experience with it, though.

F64 can precisely hold integers up to 2**53, so it's not a terrible option... but you sound like you're looking for an arbitrary precision number library.

Start with num-bigint β€” Rust math library // there, and you can use num-rational β€” Rust math library // to represent fractions. That doesn't cover everything, but really high quality calculators are actually quite tricky, you shouldn't expect a simple answer.


Well, actually.


Thank you, this ended up letting me do the job.

As an aside, note that equality of trigonometric expressions is undecidable (Richardson's theorem). Any calculator that has them will need to deal with that uncertainty – whether via rounding or otherwise.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.