0

I have a task to calculate a square root using the Newton method using a function within a function. The user enters a number that he wants to know his root and another number that is his guess to the root. The program I made works but the problem is that it only works for integer numbers. Although I convert the input to float when I set for example the number 2 and for example a guess 1 it gives me only the integer and not the decimal i mean instead of 1.4142 it gives 1. I would love to understand where the problem is. Thanks in advance !

my code :

def mySqrt2():
  
    number=float(input('enter a number that you want to find its root:'))
    n=float(input('enter your Guess:'))
    
    def mySqrt1(number,n):
        
        def checkIfGood():
            def ImprovingGuess():
                newguess=n
                i=0
                while i!=100:
                    temp=number//newguess
                    newguess=(temp+newguess)//2.0
                    i+=1
       
                return newguess
            
            if n == (number**.5):
                return 'your guess is good!'
            else:
                return ImprovingGuess()
            
        return checkIfGood()        
    return mySqrt1(number,n)

print('The result is :',mySqrt2())
Mark Dickinson
  • 29,088
  • 9
  • 83
  • 120
  • 4
    Why are you using integer division (`//` rather than `/`) if you want to work with floats? – John Coleman Oct 29 '21 at 21:56
  • And Newton's method converges really fast, doubling the number of decimal places each time. ImprovingGuess really only needs to do one iteration. – Frank Yellin Oct 29 '21 at 22:00
  • 1
    In case it isn't clear, @JohnColeman identified the problem. You're using integer division, and you shouldn't be. And Frank is also right; you will never need more than 3 or 4 iterations. 100 is silly. – Tim Roberts Oct 29 '21 at 22:14
  • Read [this article](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) for tips on debugging your code. – Code-Apprentice Oct 29 '21 at 22:16
  • As a side note, you don't need all those nested functions. Just put the code for them where you're currently calling them (with appropriately renamed variables). There's seldom a good reason to define a (non-recursive) function and then immediately call it once. If you are doing that, the function is not needed! – Blckknght Oct 29 '21 at 22:37

0 Answers0