Skip to content

Commit

Permalink
Fix values displayed by ufloat in scientific notation
Browse files Browse the repository at this point in the history
  • Loading branch information
AndrewSazonov committed Mar 11, 2024
1 parent 2eb2347 commit 6ff0c40
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions easyDiffractionApp/Logic/Helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import sys
import decimal
import importlib.util
import numpy as np
from uncertainties import ufloat

from PySide6.QtCore import Qt, QObject, QCoreApplication, Signal, Slot, Property
Expand Down Expand Up @@ -146,6 +147,23 @@ def formatMsg(type, *args):

@staticmethod
def toStdDevSmalestPrecision(value, std_dev):
if std_dev > 1:
value_str = f'{round(value)}'
std_dev_str = f'{round(std_dev)}'
value_with_std_dev_str = f'{value_str}({std_dev_str})'
else:
precision = 1
std_dev_decimals = precision - int(np.floor(np.log10(std_dev) + 1))
std_dev = round(std_dev, std_dev_decimals)
std_dev_str = f'{std_dev:.{std_dev_decimals}f}'
value = round(value, std_dev_decimals)
value_str = f'{value:.{std_dev_decimals}f}'
clipped_std_dev = int(round(std_dev * 10**std_dev_decimals))
value_with_std_dev_str = f'{value_str}({clipped_std_dev})'
return value_str, std_dev_str, value_with_std_dev_str

@staticmethod
def toStdDevSmalestPrecision_OLD(value, std_dev):
if std_dev < 10:
fmt = '.1u'
else:
Expand All @@ -154,6 +172,25 @@ def toStdDevSmalestPrecision(value, std_dev):
value_with_std_dev_str = f'{ufloat(value, std_dev):{fmt}S}'
return value_str, std_dev_str, value_with_std_dev_str

def value_with_error_WEB(val, err, precision=2):
"""String with value and error in parenthesis with the number of digits given by precision."""
# Number of digits in the error
err_decimals = precision - int(np.floor(np.log10(err) + 1))
# Output error with a "precision" number of significant digits
err_out = round(err, err_decimals)
# Removes leading zeros for fractional errors
if err_out < 1:
err_out = int(round(err_out * 10**err_decimals))
err_format = 0
else:
err_format = int(np.clip(err_decimals, 0, np.inf))

# Format the value to have the same significant digits as the error
val_out = round(val, err_decimals)
val_format = int(np.clip(err_decimals, 0, np.inf))

return f'{val_out:.{val_format}f}({err_out:.{err_format}f})'


class Converter:

Expand Down

0 comments on commit 6ff0c40

Please sign in to comment.