Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print many significant figures in Python?

Tags:

For a scientific application I need to output very precise numbers, so I have to print 15 significant figures. There are already questions on this topic here, but they all concern with truncating the digits, not printing more.

I realized that the print function converts the input float to a 10 character string. Also, I became aware of the decimal module, but that does not suit my needs.

So the question is, how can I easily print a variable amount of signifcant figures of my floats, where I need to display more than 10?

like image 486
Ingo Avatar asked Feb 23 '12 15:02

Ingo


People also ask

How do you do 3 significant figures in Python?

' + str(p) + 'e') % f) allows you to adjust the number of significant digits!

What does %d and %s do in Python?

They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.

How do you do 3 significant figures?

We round a number to three significant figures in the same way that we would round to three decimal places. We count from the first non-zero digit for three digits. We then round the last digit. We fill in any remaining places to the right of the decimal point with zeros.

How do you find the most significant digit in Python?

Assuming you're only dealing with positive numbers, you can divide each number by the largest power of 10 smaller than the number, and then take the floor of the result.


1 Answers

Let:

>>> num = 0.0012345 

For 3 significant figures:

>>> f'{num:.3}' '0.00123' 

For 3 decimal places:

>>> f'{num:.3f}' '0.001' 

See the "presentation types for floating point and decimal" table at the bottom of this section for any additional requirements provided by e, E, f, F, g, G, n, %, None.

like image 52
Mateen Ulhaq Avatar answered Oct 31 '22 21:10

Mateen Ulhaq