Skip to content

Instantly share code, notes, and snippets.

@Eddy-Barraud
Last active October 20, 2023 08:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Eddy-Barraud/680b70769f0fdd2544fda21ff0503373 to your computer and use it in GitHub Desktop.
Save Eddy-Barraud/680b70769f0fdd2544fda21ff0503373 to your computer and use it in GitHub Desktop.
A python function to correctly print a value with its error in scientific format and the correct number of significant figures.
# Return the power of ten of a string in scientific notation
# "3.42e3" --> 3
def get_power_of_ten(scientific_notation):
# Split the scientific notation into coefficient and exponent parts
coefficient, exponent = scientific_notation.split('e')
return int(exponent)
# Returns the value with significant figures up to the error position
# Example round_on_error(2.586e-1, 3.304e-2) => 2.6e-01 ± 3.3e-02
def round_on_error(val, err):
val_power_ten = get_power_of_ten(f'{val:.10e}')
err_power_ten = get_power_of_ten(f'{err:.10e}')
significant_numbers = abs(err_power_ten - val_power_ten)
significant_numbers_err = min(3,significant_numbers)
formatted_result = "{f_val:.{SN}f}e{f_exp:+03} ± {f_err:.{SNerr}f}e{f_exp_err:+03}".format(
f_val=val*10**(-val_power_ten), SN=significant_numbers, SNerr= significant_numbers_err,
f_exp = val_power_ten, f_exp_err = err_power_ten, f_err=err*10**(-err_power_ten))
formatted_value = "{f_val:.{SN}f}e{f_exp:+03}".format(
f_val=val*10**(-val_power_ten), SN=significant_numbers, f_exp = val_power_ten)
formatted_error = "{f_err:.{SNerr}f}e{f_exp_err:+03}".format(
SNerr= significant_numbers_err, f_exp_err = err_power_ten, f_err=err*10**(-err_power_ten))
return formatted_result, formatted_value, formatted_error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment