I want to display in a HTML page some datas with errors, for example:
(value, error) -> string (123, 12) -> (12 +- 1) x 10^1 (4234.3, 2) -> (4234 +- 2) (0.02312, 0.003) -> (23 +- 3) x 10^-3
I’ve produced this:
from math import log10
def format_value_error(value,error):
E = int(log10(abs(error)))
val = float(value) / 10**E
err = float(error) / 10**E
return "(%f +- %f) x 10^%d" % (val, err, E)
but I’ve some difficulties with rounding. Are there some libraries with this functionality?
I’m not sure exactly what you want, but I assume you just want to round the numbers you have to the nearest integer? If so, you can use the built-in function
round:Here’s the help:
If you want to round down you can use
floorfrommath. I think you actually want to use this after taking the logarithm, rather than just casting to int, as int(-0.5) is 0, not -1 as you want. Here’s a modified version of your program that I think does what you want:This gives the following output:
This is very close to what you want. The only difference is that the
text x 10^0should not be printed, but I’m sure you can find a solution for this. 🙂