Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the scientific formatting of Decimal(0) different from float 0?

When using Decimal(0) and formatting it to .2e format the following happens:

>>> f'{Decimal(0):.2E}'
'0.00E+2'

However if you just use 0 or 0. the following happens:

>>> f'{0.:.2E}'
'0.00E+00'

How come the results are different?

like image 614
wizard003 Avatar asked Aug 18 '20 20:08

wizard003


People also ask

How do I print float without trailing zeros?

To format floats without trailing zeros with Python, we can use the rstrip method. We interpolate x into a string and then call rstrip with 0 and '. ' to remove trailing zeroes from the number strings. Therefore, n is 3.14.

How do you print zeros after a decimal in Python?

Use the format() function to add zeros to a float after the decimal, e.g. result = format(my_float, '. 3f') . The function will format the number with exactly N digits following the decimal point. Copied!

How do you show decimals in Python?

To format decimals, we will use str. format(number) where a string is '{0:. 3g}' and it will format string with a number. Also, it will display the number with 1 number before the decimal and up to 2 numbers after the decimal.


1 Answers

In my previous answer I described how this is done in cpython, in this I will describe why. This question was raised in this discussion and most of the quotes will be from there:

Let's consider an example:

>>> x = Decimal("1e+5").quantize(Decimal("1e+10"))
>>> x
Decimal('0E+10')
>>> s = "{:.19e}".format(x)
>>> s
'0.0000000000000000000e+29'
>>> Decimal(s)
Decimal('0E+10')

The original magnitude was e+10, after formatting it's still e+10. The magnitude of the original number is kept after the formatting process.

From the point of view of decimal it's the right thing. The original magnitude should be traceable

0 is really special in the IBM specification. The magnitude is kept, the precision is not.

>>> Decimal("0e10") * Decimal("0e20") 
Decimal('0E+30')


>>> Decimal("0.000e10")
Decimal('0E+7')

So we're basically doing the reverse of the above in formatting when a precision is given.


So, if we go back to the original example of the OP:

>>> f'{Decimal(0):.2E}'
'0.00E+2'

If it returned 0.00Е+00 then the magnitude of this decimal number would be E-2:

>>> d = f'{Decimal(0):.2E}'
>>> d
'0.00E+2'
>>> Decimal(d)
Decimal('0')
>>> d = '0.00E+00'
>>> Decimal(d)
Decimal('0.00')
like image 140
alex_noname Avatar answered Oct 26 '22 08:10

alex_noname