mhogrefe / malachite

An arbitrary-precision arithmetic library for Rust.
GNU Lesser General Public License v3.0
453 stars 18 forks source link

Parsing a rational from a decimal number literal #15

Closed yannham closed 1 year ago

yannham commented 1 year ago

Is there a function anywhere to parse a rational from a decimal number literal? One obvious way is to go through primitive Rust types (say, f64), but this fails on valid rational (anything outside the bounds of an f64, for example). For example:

let r : Rational = Rational::hypothetical_exact_parse_with_a_better_name("10.50");

In fact, would that make sense to extend the parsing function to understand such a format? I reckon that f64 do parse decimal notation, and that this is a pretty common representation. {sign}{left_digits}.{right_digits} would be parsed the same as {sign}*{left_digits}{right_digits}/{10^right_digit_counts}

yannham commented 1 year ago

Ah, it seems it might be done using from_sci_string. I thought scientific notation implied that the part before the exponent should lie between 0 and base, but the examples seem to indicate otherwise.

I'm keeping open just to wait on a confirmation.

mhogrefe commented 1 year ago

Yes, from_sci_string will do what you want. There's also to_sci, which does the opposite conversion.

I didn't give these names too much thought when I created them, and you're right that they're somewhat inaccurate. (to_sci doesn't always product actual scientific notation, either.) I don't want "decimal" to be part of the name, because the functions support any base from 2 to 36. How about "from_digit_string" and "to_digit_string"?

mhogrefe commented 1 year ago

By the way, the other function is currently called to_sci rather than to_sci_string because instead of returning a String it returns a SciWrapper object, which you can call to_string on to obtain a string. The reason for this is so that you can have code like println!("x: {}", x.to_sci()); that does not always allocate memory. If to_sci returned a String then you'd be forced to allocate memory whenever you used it.

So upon further reflection, "to_digit_string" isn't an appropriate name for a function that doesn't return a string. "to_digits" wouldn't work either, because I have similarly-named functions that return Vecs of digits. Maybe I should use "to_formatted_digits".

mhogrefe commented 1 year ago

One last thing: in case you haven't found it yet, the specific documentation for the Rational implementation of FromSciString has more information and examples.

yannham commented 1 year ago

Yes, I don't have a great suggestion for names unfortunately, but as a data point I did look first for to_digits or something with "digits" in it. Could also be something like format, or format_xxx? Thanks for the precisions, anyway!