Mr.Bigg
Mr.Bigg

Reputation: 45

Return values to fixed lengths

I am trying to calculate the square root of a number using the Newton-Raphson method. This part is relatively straight forward. However, when I want to ensure that the value returned on the final answer is always to 100 decimal places, I can't seem to get it to work. I have tried on VS Code and Jupyter Notebooks, and can only seem to get it to display to 17 or 18 decimal places.

My code is:

import decimal as Dec

Dec.getcontext().prec = 100

Number = 5
bStart = 1                                                                  # Start value is 1
zStart = 1                                                                  # Start value is 1 (x0)

aCount = 0                                                                  # Iteration count
yNewNum = 0                                                                 # New value of estimate (x1)
xRoot = 0                                                                   # Used to transfer values between yNewNum and zStart

while aCount < 101:                                                         # While the difference between zStart and yNewNum is greater than 0.0000001 (7 decimal places)
    yNewNum = (zStart + (Number / zStart)) / 2                              # x1 = (x0 + (S/x0)) / 2 
    zStart = yNewNum                                                        # Replace the value x0 with the value of x1
    yNewNum = xRoot                                                         # Replace the value of x1 with the transfer value
    xRoot = zStart                                                          # Replace the transfer value with x0
    aCount += 1                                                             # aCount iterates by 1
    print()
    print(aCount, ":", Dec.Decimal(zStart))
    print(len(str(zStart)))
print("Newton-Raphson method =  ", Dec.Decimal(zStart))
print("Length:", len(str(zStart)))

The output of the last few iterations looks like this on both platforms, when the starting value is 15:

98 : 3.87298334620741702138957407441921532154083251953125

Length: 17

99 : 3.87298334620741702138957407441921532154083251953125

Length: 17

100 : 3.87298334620741702138957407441921532154083251953125

Length: 17

101 : 3.87298334620741702138957407441921532154083251953125

Length: 17

Newton-Raphson method =
3.87298334620741702138957407441921532154083251953125

Length: 17

Any suggestions on how to get the decimal places to show the 100 decimal places? Note that I have to use the Newton-Raphson method as it is a requirement.

Upvotes: 3

Views: 56

Answers (1)

Vidyadhar Rao
Vidyadhar Rao

Reputation: 333

At least one of the variable must be initialized with Decimal type in the floating point operations.

You have to use Number = Dec.Decimal(5)

Upvotes: 5

Related Questions