python uncertainties package give me wrong uncertainty

138 Views Asked by At

Im calulation uncertainties with the uncertainties Package in Python. But the package is making one starnge error. When I calculate my values in my code using

print(ufloat(x,ux))
print(uflaot(y,uy))
print(ufloat(x,ux)/uflaot(y,uy))

x,y,ux,uy are values in this case

everything works fine, but when im using variables its getting messed up and the calculated value for the uncertainty is worng.

so i used this code in my document

x and y are values i calculaded before

print(x)
print(ufloat(1.065,0.433)) # same value as y
    
print(y)
print(ufloat(0.02123,0.00866)) # same value as y


print((x)/y)
print(ufloat(1.065,0.433)/ufloat(0.02123,0.00866))

and it didnt workd the output was

1.065(433)
1.065(433)
0.02123(866)
0.02123(866)
50.16(1.17) # false uncertainty
50.2(28.9) # true uncertaintys

i used a print formate here, but the usage of the formate didnt change the value

I tryd to use the code in a nother document and defined x, y like there wore in my original dokument and everything worked just fine. ex:

x = ufloat(1.065,0.433)
y = ufloat(0.02123,0.00866)
print(x)
print(ufloat(1.065,0.433))
    
print(y)
print(ufloat(0.02123,0.00866))


print((x)/(y))
print(ufloat(1.065,0.433)/ufloat(0.02123,0.00866))

output:

1.1+/-0.4
1.1+/-0.4
0.021+/-0.009
0.021+/-0.009
50+/-29
50+/-29

thanks for your help!

1

There are 1 best solutions below

0
Patrick Lüscher On

I have just encountered the same problem with the uncertainties package. When you calculate an ufloat value from different ufloat values, the error propagation doesn't work as intended.

Here you can see a small example:

c = 3.0
x = ufloat(1, 0.5)
y = ufloat(c*x.n, c*x.s)
z = c * x

print(f"{x = }")    
print(f"{y = }")    
print(f"{z = }")    
print()
print(f"{y/x = }")
print(f"{z/x = }")

Output:

x = 1.0+/-0.5
y = 3.0+/-1.5
z = 3.0+/-1.5

y/x = 3.0+/-2.12 # expected result
z/x = 3.0+/-0    # correct nominal value, wrong uncertainty

I assume this is an error in the uncertainties package and is due to a problem with the variable assignment. My simple "solution" for is to create a copy of the ufloat variable before calculating:

import copy
z = c * copy.copy(x)
print(f"{z/x = }")

Output:

z/x = 3.0+/-2.12 # expected result

I hope this helps.