Number refuses to divide
<p>I have made a simple function called "Approx" which multiplies two numbers together then divides them by two. When I use the function by itself it works great but it seems in the hunk of code I have it doesn't divide the number in half and I have no idea why. This is my code where is the error and how can I fix it?</p>

<pre><code>import math

def Approx(low,high):
    base = low * high
    return base/2

root = float(input("What to approx the sqrt of : "))
vague = float(input("How off can it be? : "))
wrong = True
oroot = root
root = math.floor(float(root))
trunk = root + 1
step = 0
while wrong:
    if Approx(root,trunk) &gt; oroot - vague and Approx(root,trunk) &lt; oroot:
        print("Done. " + str(step) + " steps taken.")
    else:
        if Approx(root,trunk) &gt; oroot:
            temproot = root
            root = Approx(root,trunk)
            trunk = temproot
            step += 1
            print("Step " + str(step) + " finished. Approx is " + str(Approx(root,trunk)))
        else:
            temptrunk = trunk
            trunk = Approx(root,trunk)
            root = trunk
            step += 1
            print("Step " + str(step) + " finished. Approx is " + str(Approx(root,trunk)))
    if step &gt; 50:
        print("More than fifty steps required.")
        wrong = False
</code></pre>

<p>Your function works the way you describe it, however I don't understand how you use it in the rest of the code.</p>

<p>It seems like you are trying to approximate square roots using a variant of Newton's method, but it's hard to understand how you implement it. Some variables in your code are not used (what is <code>temptrunk</code> for ?), and it's hard to determine if it's intended or a mistake.</p>

<p>If it is indeed the newton method you'd like to implement, you'll want to have an approximation function that converges to the target value. In order to do that, you compute the arithmetic mean of a guess and your target value divided by this guess (<code>new_guess = mean([old_guess, target/old_guess])</code>). Once you have that, you just need to compare the difference between <code>new_guess</code> and <code>target</code>, and once it reaches a given threshold (in your code, <code>vague</code>), you can break of the loop.</p>

<p>There are multiple ways to improve other aspects of your code:</p>

<ul>
<li>I'd advise against using a sentinel value for breaking out of the loop, <code>break</code> statements are more explicit.</li>
<li><p>You can directly make a loop have maximum number of steps, with :</p>

<pre><code>for step in range(MAX_STEPS):
    guess = ... # try to guess
    if abs(target - guess) &lt; delta:
        break
else:
    print("Maximum steps reached.")
</code></pre>

<p>The <code>else</code> block will only be called if <code>break</code> is <strong>not</strong> reached.</p></li>
</ul>

python python-3.x