I need to keep track of the number of significant digits in a number (float or integer). Trailing zeroes after a decimal point are considered significant, e.g. in 12.0 there are 3 significant figures and in 12.00 there are 4. I thought to use something like len(str(number))
but this removes all but one of the trailing zeroes from floats. The format()
function and str.format()
method, often suggested for similar questions (in integer, in float, and float again) would both seemingly require me to know in advance how many decimal points I wanted. Is there a good way to go about this? Should I just require the number to be inputted as a string so that all trailing zeroes are preserved? The code I'm using to find significant figures is below. I believe that it works for all cases except that described above.
def __init__(self, value):
"""Initializes a Sigfig object with the given value and finds the number of significant figures in value"""
assert type(value)==int or type(value)==float or type(value)==Sigfig, "Sigfig value must be of type int, float, or Sigfig"
# I wanted to avoid values of type str so that I don't have to worry about inputs like Sigfig('55b')
self.value=value #This is to allow math with full value to avoid losing precision to rounding
self.valuestring=f'{value}'
#Remove leading zeroes before or after a decimal point and scientific notation
self.remlead0enot=self.valuestring.lstrip('0').lstrip('.').lstrip('0').split('e',1)[0]
#Account for ambiguous zeroes before implied decimal point e.g. 1000
if '.' not in self.valuestring and self.valuestring[-1]=='0':
self.sigfigs=len(self.remlead0enot.rstrip('0'))
#Account for floats e.g. 1.005 and ints e.g. 105
else:
self.sigfigs=len(self.remlead0enot)-1 if '.' in self.remlead0enot else len(self.remlead0enot)
CodePudding user response:
I'm not sure what you want to achieve but if if your question is if you can make a float remember with how many trailing zeros it was stored with: No.
You can only define how many points after the comma should be included when you convert the float to a string. But the float itself has no concept about significant digits. (Aka: 3.000000f == 3.0f
)
If you need to know the amount of trailing zeros, yes, you need the input to be a string.
When you already have a string though you can also just store how many numbers are after the .
.
arg_as_str = "3.100"
decimal_points = len(arg.split(".")[1]) # 3
as_float = float(arg) # 3.1
...
output_as_str = f"{as_float:{decimal_points}f}" # "3.100"
Hope that was helpful.
CodePudding user response:
You can look into the package mpmath
. This package is made specifically for this purpose, to allow arbitrary precision of floats.