How to print floating point numbers, like without truncation in python?

I have a number 0.0000002345E ^ -60. I want to print the floating point value as it is. How to do it? print% f truncates it to 6 digits. Also% n.nf gives fixed numbers. How to print without truncation.

+4
source share
3 answers

Like this?

>>> print('{:.100f}'.format(0.0000002345E-60))
0.0000000000000000000000000000000000000000000000000000000000000000002344999999999999860343602938602754

As you can see from the results, it is not entirely clear how you want to do this. Because of the floating-point representation, you lose precision and cannot represent the number exactly. Therefore, it is not entirely clear where you want the number to stop displaying.

, , .

decimal - :

>>> from decimal import Decimal
>>> d = Decimal('0.0000002345E-60')
>>> p = abs(d.as_tuple().exponent)
>>> print(('{:.%df}' % p).format(d))
0.0000000000000000000000000000000000000000000000000000000000000000002345
+2

, float?

, float.

. , , float, .

, , , , , , .

, :

{: g} {: G}, , , E ). e E, 0s .

, my_float, "{:G}".format(my_float) , Python. , .

- float , , poke , float Decimal.

- , - . 'max_digits' sys.float_info.max_10_exp 14, . import sys - .

:

import math
import sys

def precision_and_scale(x):
    max_digits = sys.float_info.max_10_exp
    int_part = int(abs(x))
    magnitude = 1 if int_part == 0 else int(math.log10(int_part)) + 1
    if magnitude >= max_digits:
        return (magnitude, 0)
    frac_part = abs(x) - int_part
    multiplier = 10 ** (max_digits - magnitude)
    frac_digits = multiplier + int(multiplier * frac_part + 0.5)
    while frac_digits % 10 == 0:
        frac_digits /= 10
    scale = int(math.log10(frac_digits))
    return (magnitude + scale, scale)

f = 0.0000002345E^-60

p, s = precision_and_scale(f)

print "{:.{p}f}".format(f, p=p)

, , Decimal, , , .

0

decimal.Decimal:

>>> from decimal import Decimal
>>> str(Decimal(0.0000002345e-60))
'2.344999999999999860343602938602754401109865640550232148836753621775217856801120686600683401464097113374472942165409862789978024748827516129306833728589548440037314681709534891496105046826414763927459716796875E-67'

float, 0.0000002345e-60. , float python, 0.0000002345 * 10**-60.

floatshould be used for approximate calculations. If you want accurate results, you should use something else, like the one mentioned Decimal.

0
source

All Articles