0

There is a useful recent feature in python allowing one to print a variable's name and its value: https://stackoverflow.com/a/57225950/6843348. This doesn't quite work with the uncertainties library's ufloat type, because the representation is printed, losing the formatting. Any suggestion to work around this?

from uncertainties import ufloat

x = ufloat(1.8768768, 0.0039788594)
print(x) # OK: 1.877+/-0.004
print(repr(x)) # 1.8768768+/-0.0039788594
print(f"{x=}") # Not OK: x=1.8768768+/-0.0039788594

EDIT Would prefer to enter the var name only once, and keep ufloat's formatting

Mister Mak
  • 276
  • 1
  • 9

2 Answers2

0

Change your print statement to:

print(f'x={x}')
0

I HOPE YOU ARE DOING GREAT!!! While using f-strings to print the variable name and its value with uncertainties' ufloat type, you can define a custom function that extracts the nominal value and standard deviation separately. FOR EXAMPLE:

from uncertainties import ufloat

def print_ufloat(var_name, value): nom_value = value.nominal_value std_dev = value.std_dev

print(f"{var_name}={nom_value:.3f}+/-{std_dev:.3f}")

x = ufloat(1.8768768, 0.0039788594) print_ufloat('x', x)

Using this custom function, you can preserve the desired formatting for printing variable names and their values when working with uncertainties' ufloat type.

  • Thanks! My impression is your solution requires to enter the var name and value, and overrides ufloat's formatting. Have edited question to clarify that point. – Mister Mak May 26 '23 at 21:30