[Python] Why no floating point error occurs in print(0.1* 100000) vs (Decimal(0.1)*100000) due...

Discussão em 'Python' iniciado por Stack, Abril 17, 2025.

  1. Stack

    Stack Membro Participativo

    I am studying numerical analysis and I have come across this dilemma.

    Running the following script,

    from decimal import Decimal
    a = 0.1 ;
    N = 100000 ;

    # product calculation
    P = N*a

    # Print product result with appearent no error
    print(' %.22f ' % P)
    # Print product result with full Decimal approssimation of 0.1
    print(Decimal(0.1) * 100000)


    i realized that despite 0.1 not having an accurate floating-point representation, when I multiply it by 100000 (which has an exact floating-point representation), and increase the precision of how I print the result, I do not notice any error.

    print(' %.22f ' % P) # Result: 10000.0000000000000000000000


    This is in contrast to the case where I use the Decimal method, where I can see the error behind the product.

    print(Decimal(0.1) * 100000)


    Can anyone explain why this happens?

    Continue reading...

Compartilhe esta Página