# Modifying the value of a float-like object

Peter Otten __peter__ at web.de
Tue Apr 14 18:26:16 CEST 2009

```Eric.Le.Bigot at spectro.jussieu.fr wrote:

> Alternatively, I'd be happy with a way of handling numerical
> uncertainties in Python calculations (such as in "calculate the value
> and uncertainty of a*sin(b) knowing that a=3.0 +/- 0.1 and b=1.00 +/-
> 0.01").

Naive no warranties implementation:

from math import sin, sqrt

class Value(object):
def __init__(self, value, err):
self.value = value
self.err = err
def __str__(self):
return "%s +- %s" % (self.value, self.err)

def derive(f, values, i, eps=1e-5):
x1 = f(*values)
values = list(values)
values[i] += eps
x2 = f(*values)
return (x2-x1)/eps

def calc(f, *args):
values = [v.value for v in args]
errs = [v.err for v in args]

sigma = 0
for i, (v, e) in enumerate(zip(values, errs)):
x = derive(f, values, i)*e
sigma += x*x
return Value(f(*values), sqrt(sigma))

a = Value(3.0, 0.1)
b = Value(1.0, 0.01)

def f(x, y):
return x * sin(y)

print "a = %s" % a
print "b = %s" % b
print "c = %s" % calc(f, a, b)

Peter

```