views:

81

answers:

2

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?

+3  A: 

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:

>>> int(round(1.5))
2

Here's the help:

>>> help(round)
Help on built-in function round in module __builtin__:

round(...)
    round(number[, ndigits]) -> floating point number

    Round a number to a given precision in decimal digits (default 0 digits).
    This always returns a floating point number.  Precision may be negative.

If you want to round down you can use floor from math. 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:

from math import log10, floor
def format_value_error(value,error):
    E = int(floor(log10(error)))
    val = int(round(float(value) / 10**E))
    err = int(round(float(error) / 10**E))
    return "(%d +- %d) x 10^%d" % (val, err, E)

print format_value_error(123, 12)
print format_value_error(4234.3, 2)
print format_value_error(0.02312, 0.003)

This gives the following output:

(12 +- 1) x 10^1
(4234 +- 2) x 10^0
(23 +- 3) x 10^-3

This is very close to what you want. The only difference is that the text x 10^0 should not be printed, but I'm sure you can find a solution for this. :)

Mark Byers
it's more complicated. I know the round function, but I need to calculate the second arguments to round (ndigits)
wiso
@wiso: Does my updated answer help you?
Mark Byers
very good! Thanks
wiso
Here the results: http://www.mi.infn.it/~turra/900GeV/stats/(the second column is forced to have the same exponentian than the first)
wiso
Is there a problem with `(-542±13)×103`... shouldn't ±13 be impossible?
Mark Byers
I think there might also be an issue with `format_value_error(0, 99)`: it gives output `(0 +- 10) x 10^1` instead of `(0 +- 1) x 10^2`.
Mark Byers
A: 

You could use this in Mark's solution to blank the exponent for 10^0

    if E:
        return "(%d +- %d) x 10^%d" % (val, err, E)
    else:
        return "(%d +- %d)" % (val, err)
gnibbler