Reputation: 1291
Given this simple python script:
import sys, math
for i in range(1, len(sys.argv)):
num = float(sys.argv[i])
print('sin(%f) = %f' % (num, math.sin(num)))
Run with these arguments:
python hw2a.py 1.4 -0.1 4 99
I want this output:
sin(1.4)=0.98545
sin(-0.1)=-0.0998334
sin(4)=-0.756802
sin(99)=-0.999207
However when I run it, I get a lot of insignificant digits (well, zeroes) behind the decimal point and the significant digits. I know I can specify a fixed number of decimals using for instance %.3f, but how can I make it print all digits behind the decimal point, until there are no significant digits left?
Thanks in advance!
Upvotes: 1
Views: 1672
Reputation: 180441
Use sys.argv[i]
, no need to convert i to a float and back to a string and g
to format:
import sys, math
for i in range(1, len(sys.argv)):
num = float(sys.argv[i])
print "sin({}) = {:g}".format(sys.argv[i],math.sin(num))
python foo.py 1.4 -0.1 4 99
sin(1.4) = 0.98545
sin(-0.1) = -0.0998334
sin(4) = -0.756802
sin(99) = -0.999207
If the data is not manually entered as @mhawke suggests, you can use:
print "sin({:g}) = {:g}".format(num, math.sin(num))
Upvotes: 2
Reputation: 11734
You can format with %g
:
In [16]: a = [1.4, -0.1, 4, 99]
In [18]: for num in a:
...: print('sin(%g) = %g' % (num, math.sin(num)))
...:
sin(-0.1) = -0.0998334
sin(4) = -0.756802
sin(99) = -0.999207
Upvotes: 4