Mike C
Mike C

Reputation: 13

Why are my decimal places not counting correctly?

I am trying to print pi with a specific number of decimal places based on an input. When I enter 99 decimal places, it prints out 99. When I enter 100 decimal places, it only prints out 99. When I enter 101 decimal places it prints out 101. I want to be able to limit it to 100 decimal places. I am new to python and trying to work an exercise. Here is my code:

from mpmath import mp

def pi_decimals():
    while True:
        spaces = int(input('How many decimal places do you wish to use? '))
        
        if spaces not in range(0,102):
            print('Enter a number between 0 and 100!')
            continue
        else:
            mp.dps = int(spaces) + 1
                        
        print(mp.pi)
        break

pi_decimals()

Upvotes: 0

Views: 100

Answers (1)

Grismar
Grismar

Reputation: 31319

The issue is that a value ending in a 0 at the end of the decimals won't print that 0. Compare mp.dps values 32, 33 and 34 (where a 0 occurs naturally in pi). At the position where you're looking at, the value would end in a 9, but since the next digit is >= 5, it rounds to a 0 and doesn't print.

However, see this:

from mpmath import mp

for dps in [32, 33, 34, 100, 101, 102]:
    mp.dps = dps
    s = str(mp.pi)
    print(s, len(s))

for dps in [32, 33, 34, 100, 101, 102]:
    s = mp.nstr(mp.pi, dps, strip_zeros=False)
    print(s, len(s))

Result:

3.1415926535897932384626433832795 33
3.1415926535897932384626433832795 33
3.141592653589793238462643383279503 35
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068 101
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068 101
3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798 103
3.1415926535897932384626433832795 33
3.14159265358979323846264338327950 34
3.141592653589793238462643383279503 35
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068 101
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170680 102
3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798 103

So, I think you're looking for mp.nstr(mp.pi, dps, strip_zeros=False) to get the result you want printed.

Upvotes: 1

Related Questions