Please click on ads

Please click on ads

Wednesday, 6 November 2024

Write a Python Program to find the square root of a number by Newton’s Method.

 Object: Write a Python Program to find the square root of a number by 

Newton’s Method 

Newton’s Method

1. Define a function named newtonSqrt(). 

2. Initialize approx. as 0.5*n and better as 0.5*(approx. +n/approx.) 

3. Use a while loop with a condition better!=approx. to perform the following,

i. Set approx.=better

ii. Better=0.5*(approx.+n/approx.) 

4. Print the value of approx.


Source Code:

defnewton_method(number, number_iters = 500):

 a = float(number) # number to get square root of

fori in range(number_iters): # iteration number

number = 0.5 * (number + a / number) # update

 # x_(n+1) = 0.5 * (x_n +a / x_n)

return number

printnewton_method(9)

# Output: 3

printnewton_method(2)

# Output: 1.41421356237




No comments:

Post a Comment