1

Given the .5 in avg_guess - do I need all the float(arg) specifications?

# Heron of Alexandria method for approximating
# the square root of a number

def heron(num, guess, tolerance):
    print "Your guess squared:",guess**2
    if guess**2 != num:
        print "When squared, the guess:", guess, "is",abs(float(num) - float(guess)**2), "away from", num, "\n"
        if abs(float(num) - float(guess)**2) > float(tolerance):
            avg_guess = 0.5 * (float(guess) + (float(num) / float(guess)))
            return heron(num, avg_guess, tolerance)
        print "Given your tolerance, this is Heron's best guess:", guess, "\n"
    else:
        print guess, "is correct!\n"

I noticed that to a certain tolerance, this function will return 5.0 as the answer... Not sure why?

heron(25, 3, .00000001)

returns 5.0 from the "else:" condition, but

heron(25, 3, .0000001)

terminates from the tolerance in the initial nested "if:" condition, printing: Given your tolerance, this is Heron's best guess: 5.00000000233.

MmmHmm
  • 3,435
  • 2
  • 27
  • 49
  • 1
    Please, only one question per posting. Testing for numbers including an optional decimal place (and a +- sign?) is a little more complicated than you might think, and could involve using a regular expression. In python 2 use `raw_input()`, `input()` has a specialised use in Python 2 (but is used in Python 3). Don't use `type()`, use `isinstance()`. If you are starting out I strongly recommend you use Python 3 rather than Python 2, it is far superior and easier to use - but of course that's subjective. – cdarke Apr 03 '16 at 07:29
  • thank you cdarke - will do! – MmmHmm Apr 03 '16 at 07:37
  • 1
    To clarify, we like postings to be useful to as many people as possible. Clearly more people might be interested in checking for a number than there are in Heron's formula. But of course that has been asked before: http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float-in-python. Decomposing a process into discrete independent steps is a good discipline to learn anyway, and please search for existing postings before posting your own - you will find several for Heron's formula. – cdarke Apr 03 '16 at 07:48
  • okay - thank you for the suggestion regarding good programming discipline. Should I just delete this post? – MmmHmm Apr 03 '16 at 20:09
  • 1
    Along with the above points, including a story along with your post isn't really necessary. You should be posting simply a question, not some background story on how or why you need to ask the question – OneCricketeer Apr 04 '16 at 06:12
  • Okay - noted, thank you (I know - "thank you"s are more noise in the signal) – MmmHmm Apr 04 '16 at 06:46

0 Answers0