Python - Square root estimate

Asked

Viewed 111 times

0

Good, I was here solving an exercise where the program asks the user for a positive number and calculates its square root using: +=(+ã/) / is an estimate for the square root of the number; + is the next estimate based on the previous estimate. The first estimate of the square root should be = U/ . The calculation of the next estimate should continue while the difference |+|>.

The code I have is:

# coding: iso-8859-1 -*-
import math
print('Programa que calcula a raiz quadrada')
print()
while True:
    numero=eval(input('Introduza um número positivo: '))
    if 0<numero:
        break
    else:
        print('O número introduzido tem de ser positivo')
        print() 
Cont=0
Ri1=1
Ri=0
while abs(Ri1-Ri)>0.0001:
    if Cont==0:
        Ri=numero/2
        Cont=Cont+1
    else:
        Ri1=(Ri+numero/Ri)/2
        Ri=Ri1
        Cont=Cont+1
print(numero)
print(Cont)
print(Ri1)

As I am still at the beginning of the programming I can only use if and while. Supposedly Estimate 1 = Ri=number/2 Estimate 2 = =(+ã/)/ Estimate 3 = +=(+ã/)/ ... one of the results that should give would be: Number=2; Number of Estimates =5; Result=1.414214

  • What mistake are you finding?

  • I am not making a mistake, but the result is going wrong

1 answer

1


You must save the last approach before calculating the next:

[...]
    else:
        Ri1=(Ri+numero/Ri)/2
        Ri=Ri1
        Cont=Cont+1
[...]

On the second line, the command Ri=Ri1 makes the two numbers equal, that is, once you exit the loop, the difference between them will be 0.

Try reversing the order of the lines:

[...]
    else:
        Ri=Ri1
        Ri1=(Ri+numero/Ri)/2
        Cont=Cont+1
[...]

Running, we find the desired result:

Programa que calcula a raiz quadrada

Introduza um número positivo: 81
81
8
9.000000000007091

Another problem found, is that your initial kick of Ri1 is already 1. I mean, if numero is 2, the first approximation will be 1 and will come out of the loop in the first iteration. A hint would be to give the initial value of the correct variables from the beginning:

Cont=1
Ri1=numero/2
Ri = 0
while abs(Ri-Ri1)>0.0001:
    Ri=Ri1
    Ri1= (Ri1+numero/Ri1)/2
    Cont=Cont+1
  • I just tested with your number entered (81) and the result gives the intended but when I put number=2 the result already goes wrong since with number=2 the results should be: number=2, cont=5, Ri1=1.414214... and the result you are giving me is number=2, cont=1, Ri1=1

  • Yes. It’s a mistake because the first kick is R = numero/2. How you gave the initial value of the variable Ri1 of 1, matches the first kick and the while already returns false. I edited my answer to include a solution to this too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.