I need to make a program that read 2 input: 1st contains a non-negative integer n, not greater than 1 billion (109), 2nd contains a non-negative integer k (the desired precision measured in fractional digits), not greater than 10 thousand (104). The program should print out a single number to the standard output. That number should be the square root of n, taken with precision of k fractional digits, always rounding down whenever some rounding is needed. (In case when k = 0 the result should be rounded down to the nearest integer).
This is my second task and I wrote the below code to calculate it using the Newton's Method.
The program can freely assume that the input will meet the above conditions
The progam works but the number of decimal positions is not correct always, to solve this, I tried to add some condition in order to increase the getcontext().prec of one unity according to the first number read. But did not solve the problem since for: - x < 10^2 : Result correct - x >= 10^2 & x < 10^4: Resul correct unitl x = 3000, then, the decimal position are incorrect of -1.
from decimal import *
from _decimal import Decimal
def sqrt(x):
last_guess = x/2.0
error = (1/(10**y))
while True:
guess = Decimal((last_guess + x/last_guess )/2)
if abs(Decimal(guess) - Decimal(last_guess)) < error: # example threshold
return Decimal(guess)
last_guess = Decimal(guess)
print(last_guess)
x = int(input("Calculate the square root of : "))
y = int(input("Decimal positions : "))
if x < 10**2:
getcontext().prec = y + 1
if x >= 10**2 and x < 10**4:
getcontext().prec = y + 2
if x >= 10**4 and x < 10**6:
getcontext().prec = y + 3
if x >= 10**6 and x < 10**8:
getcontext().prec = y + 4
if x >= 10**8 and x < 10**10:
getcontext().prec = y + 5
if x >= 10**10 and x < 10**12:
getcontext().prec = y + 6
if x >= 10**12 and x < 10**14:
getcontext().prec = y + 7
a =sqrt(x)
if x < 10**2:
getcontext().prec = y + 1
if x >= 10**2 and x < 10**4:
getcontext().prec = y + 2
if x >= 10**4 and x < 10**6:
getcontext().prec = y + 3
if x >= 10**6 and x < 10**8:
getcontext().prec = y + 4
if x >= 10**8 and x < 10**10:
getcontext().prec = y + 5
if x >= 10**10 and x < 10**12:
getcontext().prec = y + 6
if x >= 10**12 and x < 10**14:
getcontext().prec = y + 7
print("The square root of ",x," is : ", Decimal(a))
# print("The original number: ", Decimal(a)**2)
For the input
8765 8
your program should print out
93.62157870
For the input
3000 3
your program should print out
54,772