mathnet / mathnet-symbolics

Math.NET Symbolics
http://symbolics.mathdotnet.com
MIT License
341 stars 66 forks source link

Format for display floating numbers #29

Open FoggyFinder opened 7 years ago

FoggyFinder commented 7 years ago

It seems, that currently formatting for display floating numbers (type approximation) not very convenient.

open MathNet.Symbolics

let culture = System.Globalization.CultureInfo.InvariantCulture

"0.4095999999999994*x+13.5387777776*y"
|> Infix.parseOrUndefined
|> Infix.format
|> printfn "%s" // => 0.409599999999999*x + 13.5387777776*y

I think that better round off a number to 5-6 decimals before formatting:

open System
let test_f1 = 0.409123554
let test_f2 = 0.4123

//current
test_f1.ToString(culture) |> printfn "%s" // => 0.409123554
test_f2.ToString(culture) |> printfn "%s" // => 0.4123

//one option
test_f1 |> printfn "%f" // => 0.409124
test_f2 |> printfn "%f" // => 0.412300

//second option
let round6 (v : float) = Math.Round(v, 6)
(test_f1 |> round6).ToString(culture) 
|> printfn "%s" // => 0.409124
(test_f2 |> round6).ToString(culture) 
|> printfn "%s" // => 0.4123

I like both options though second more usual for me

cdrnet commented 7 years ago

Maybe this should be customizable, along the lines of test_f1.ToString(format, culture) where format would default e.g. to "g" but could be provided by the user as e.g. "0.00".

On the other hand, such flexible customization would deviate more from the standard notation idea (which is why we fix the culture), i.e. we could no longer guarantee a distinct meaning and round-trip parseability. But this might be ok, as long as users are aware of it.

FoggyFinder commented 7 years ago

thus, these customizable functions will receive something like configuration object as one of parameters. It's seems, that will be not very convenient if it's will be only for output ('format') without input (parse).

Not sure I understand how difficult it is to implement.