Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
custom sqrt
#1
I am attempting to create a sqrt function using mainly recursion with the use of a lambda.
I picked the code up from a book "Functional Python Programming 2ed".
The example is shown in the 1st chapter.
#!/usr/bin/python3

def next_(n, x):
    return (x+n/x)/2

n = 2 # converge value
f = lambda x: next_(n,x)

y=1.0 # seed value

def repeat(f, a):
    yield a
    for v in repeat(f, f(a)):
        yield v

def within (tolerance, iterable):
    def head_tail(tolerance, a, iterable):
        b = next(iterable)
        if abs(a-b) < tolerance: return b
    return head_tail(tolerance , next(iterable), iterable)

def sqrt(y, tolerance, n):
    return within(tolerance, repeat(f, y))

# show the square root of
print(sqrt(1.0, .0001, 3))
the final print however shows up as None.
Reply
#2
The problem is that head_tail() can return None if abs(a-b) is not smaller than tolerance. There must be something missing in that function.
Reply
#3
Just askin' as I am not quite following the logic, in the within function, did you mean to use next() or next_()? I'd recommend avoiding defining a function with a name so close to a standard library function.
Reply
#4
I modified
if abs(a-b) < tolerance: return b
to
if abs(a-b) <= tolerance: return b
When I run the code on my work pc, the sqrt appears as expected, for example:
[Image: view?usp=sharing]
But when I run the same code on my laptop, None appears.
Both are running Python 3.7.3
logoslog
Reply
#5
That's a simple fix, as shown here:
Image
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  from 50 random numbers printing only the sqrt(...)==0 AFKManager 1 2,421 Jan-12-2019, 08:16 PM
Last Post: ichabod801
  math.sqrt / pow() rounding small floats, workaround? robertHTompkins 7 3,961 Dec-22-2018, 10:58 PM
Last Post: robertHTompkins
  Accuracy of sqrt vndywarhol 1 2,527 Aug-29-2018, 10:14 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020