How do I write this mathematical expression with nested divisions in Python? - python

I'm having trouble writing this expression for the entry level certification course I'm taking.

Don't use images, instead copy and paste the code.
That question is probably for you to learn how to use parenthesis:
1/(x+1/(x+1/(x + 1/x)))

def foo(x):
return 1 /(x + 1 / (x + 1 / (x + 1.0 / x)))

Looking at this problem strongly suggests recursion to me. I'm not a huge fan of recursion in python, so I would probably implement this as a loop, but I suspect the question is meant for recursion.
How about we define a recursive method like:
def recursive_div(depth, x, y=0):
if depth==1:
return x + 1 / x
return y + 1 / recursive_div(depth-1, x, x)
Then we can do a:
print(recursive_div(4, 2))
We can verify this with one of the other answers:
def foo(x):
return 1.0 /(x + 1.0 / (x + 1.0 / (x + 1.0 / x)))
print(foo(2) == recursive_div(4, 2))

Related

How to relate a lambda function with a def function in Python?

I just enrolled to a Data Science training course. In the pre-work for Data Science, there is some "basic" python stuff and I am learning the def functions, as well as the lambda functions.
Below you can find a combination of both, but I have no idea how it actually works and what is the process flow.
The code I do not understand how it works is the following:
def func(x):
return lambda y: (x + y + 1)
def func1(x):
return lambda y : (func(x)(x)+y+1)
print(func1(3)(1))
And the returned value is:
9
def func(x):
return lambda y: (x + y + 1)
def func1(x):
return lambda y : (func(x)(x)+y+1)
print(func1(3)(1))
Functions in python are 1st class citizens, therefore you might create functions which returns function. This feature is used here in both defs. Note that call look as follows
func(x)(x)
func1(3)(1)
as first parts (func(x) and func1(3)) returns functions which are then called with single arguments (x and 1)
This is purposefully convoluted code and you will not see such a code in real life. And if you do, then run away from that company or project as fast as you can. And regarding to your understanding, try to expand the function calls the same way as you expand mathematical formulas. If you understand what lambda is, then it should be easy to expand this step by step.
So we want to evaluate this func1(3)(1). Lets dig into it step by step.
Step1: Lets' start with the first part:
func1(3) ==> lambda y: (func(x)(x) + y + 1) where x is 3 ==> lambda y: (func(3)(3) + y + 1)
Step2: Let's have a look at this part:
func(3) ==> lambda y: (x + y + 1) where x is 3 ==> lambda y: (3 + y + 1)
Step3: Now let's go one step further:
func(3)(3) ==> (3 + y + 1) where y is 3 ==> 3 + 3 + 1 ==> 7
Step 4: now let's get back to the result from step 1:
lambda y: (func(3)(3) + y + 1) ==> lambda y: (7 + y + 1)
Step 5: and now lets put this all together:
func1(3)(1) ==> (7 + y + 1) where y is 1 ==> 9
i will try my best.
im experimenting with the code and do something with the first function
it will look like this :
def func(x):
return lambda y: (x + y + 1)
print(func(3)(1))
the interesting part is you actually can put the lambda value beside the the function value so lambda value will be 1 and function value will be 3 then the result would be:
3 + 1 + 1 = 5
now the hard part that take me long to quite understand it
because its tricky.
def func(x):
return lambda y: (x + y + 2)
print(func(3)(1))
def func1(x):
return lambda y : (func(x)(x)+y+1)
print(func1(4)(1))
i see something tricky in this code, like:
4 + 4 + 1 + 1 = 10
like where is the other value to get the number to be 12
and that is where it get the value from the above function that is 2 to be putted in the function and the result would be:
4 + 4 + 1 + 1 + 2 = 12
that's what i know.
now my brain is hot.

python How to convert the input value into a mathematical function

How to convert an input value into a function!
x = int(input('Enter x value: '))
n = str(input('Enter n value: ')) #n= 2 * x ^ 2 - 2 * x + 2
def f(x,n):
return 2 * x ^ 2 - 2 * x + 2
Actually for what i understand, you don't need to input n.
x = int(input('Enter x value: '))
def f(x):
return 2*x**2 - 2*x+2
n = f(x)
Edit, after rereading others answer yes it probably wanted eval()
Just You can't write "2 * x ^ 2 - 2 * x + 2", the correct way is x**2 instead of x^2
You mean (?):
def f(x, n):
return n*x**2 - 2*x + 2
Or do you mean actually changing the operators?
The question as currently posed is mathematically impossible. You define x & n and are returning a function that you may or may not want to equate to n but its all defined entries.
Still guessing a little at the actual question, but if
y = input("Enter equation to evaluate")
and you expect y to be a quadratic, i.e.:
y = "a*x**b - c*x + d"
then you can get all them from:
import re
y1 = re.split('[* ]',y)
a = y1[0]
b = y1[3] #as there is a null ent between the ** we skip y1[2] and y[1] is 'x'
c = y1[5]
d = y1[8]
If you wanted the operators, then it gets a little harder to follow. So we'll cross that bridge if you do need them.
Or, as the others suggest, just use eval()!!
You could try to use eval.
x=int(input('...'))
n=input('...') # note that input returns a string
def f(x):
global n
return(eval(n))
I think,you are asking .
How to convert an input value into a mathmetical expression ?
If it is so !
use eval()
in python

How to integrate expressions with sympy?

I have a problem integrating an expression:
I need to integrate all terms regardless of the variable,
the expression: -x + 2 * (x - 1)
Expected result: -x**2/2 + 2 * ((x - 1)**2) / 2
the code I'm using:
from sympy import *
x = symbols('x')
expr = - x + factor(2 * (x - 1))
int_1 = integrate(expr)
print(int_1)
generated result: x**2/2 - 2*x
I'm a python beginner...
Thank you!
If you check your result you will find it is the same as the original equation, so the answer is right:
>>> eq = -x + factor(2 * (x - 1))
>>> integrate(eq).diff()
x - 2
>>> eq.expand()
x - 2
This means that the result you got differed from the expected results by a constant and such cases are considered correct in terms of indefinite integration.
It looks like you already learned about autoexpansion (thus the use of factor to keep the 2 from distributing). What you may not realize, however, is that once you pass an expression to a routine it is not required to keep your expression in factored form. It looks like you were expecting that the x - 1 would be treated like x. We can simulate that as
>>> integrate(-x)+integrate(2*y).subs(y,x-1)
-x**2/2 + (x - 1)**2
Using y to represent x - 1 is ok in this case since the results only differ by a constant:
>>> (integrate(x-1) - integrate(y).subs(y ,x-1)).is_constant()
True
It will not, however, be true for all functions of x.
The problem is that you didn't pass any integration limits (from and to), so the only possible answer was the integrated formula.
If for example you want to integrate from 0 to inf, you need to pass this instead
from sympy import *
x = symbols('x')
expr = - x + factor(2 * (x - 1))
int_1 = integrate(expr, (x,0, float('inf')))
print(int_1)
replace 0 and/or float('inf') by any numbers you want to evaluate.

Python: What is the easiest way to define a circle and check if a point lies in it

I want to define a circle of set radius, ask the user for input of the x and y coordinate and then check if the point lies within the circle.
This is what I am using right now (distance formula).
r = 1024
xc = r
yc = 6
def distance(x,y):
return ((x - xc)^2 + (y - yc)^2)^1/2
def check(x,y):
if distance(x,y) > r:
return 1;
else:
return 0;
Is there a more efficient way to do this?
I think this should work too:
if (x-xc)**2+(y-yc)**2 < r**2:
return 1
else:
return 0
but it's not very more efficient than your code , a little improve
You can simplify your check a little bit by removing the if .. else as:
def check(x,y):
return ((x - xc)**2 + (y - yc)**2) < r**2

Python, square root function?

I have compiled multiple attempts at this and have failed miserably, some assistance would be greatly appreciated.
The function should have one parameter without using the print statement. Using Newton's method it must return the estimated square root as its value. Adding a for loop to update the estimate 20 times, and using the return statement to come up with the final estimate.
so far I have...
from math import *
def newton_sqrt(x):
for i in range(1, 21)
srx = 0.5 * (1 + x / 1)
return srx
This is not an assignment just practice. I have looked around on this site and found helpful ways but nothing that is descriptive enough.
This is an implementation of the Newton's method,
def newton_sqrt(val):
def f(x):
return x**2-val
def derf(x):
return 2*x
guess =val
for i in range(1, 21):
guess = guess-f(guess)/derf(guess)
#print guess
return guess
newton_sqrt(2)
See here for how it works. derf is the derivative of f.
I urge you to look at the section on Wikipedia regarding applying Newton's method to finding the square root of a number.
The process generally works like this, our function is
f(x) = x2 - a
f'(x) = 2x
where a is the number we want to find the square root of.
Therefore, our estimates will be
xn+1 = xn - (xn2 - a) / (2xn)
So, if your initial guess is x<sub>0</sub>, then our estimates are
x1 = x0 - (x02 - x) / (2x0)
x2 = x1 - (x12 - x) / (2x1)
x3 = x2 - (x22 - x) / (2x2)
...
Converting this to code, taking our initial guess to be the function argument itself, we would have something like
def newton_sqrt(a):
x = a # initial guess
for i in range(20):
x -= (x*x - a) / (2.0*x) # apply the iterative process once
return x # return 20th estimate
Here's a small demo:
>>> def newton_sqrt(a):
... x = a
... for i in range(20):
... x -= (x*x - a) / (2.0*x)
... return x
...
>>> newton_sqrt(2)
1.414213562373095
>>> 2**0.5
1.4142135623730951
>>>
>>> newton_sqrt(3)
1.7320508075688774
>>> 3**0.5
1.7320508075688772
In your code you are not updating x (and consequently srx) as you loop.
One problem is that x/1 is not going to do much and another is that since x never changes all the iterations of the loop will do the same.
Expanding on your code a bit, you could add a guess as a parameter
from math import *
def newton_sqrt(x, guess):
val = x
for i in range(1, 21):
guess = (0.5 * (guess + val / guess));
return guess
print newton_sqrt(4, 3) # Returns 2.0
You probably want something more like:
def newton_sqrt(x):
srx = 1
for i in range(1, 21):
srx = 0.5 * (srx + x/srx)
return srx
newton_sqrt(2.)
# 1.4142135623730949
This both: 1) updates the answer at each iteration, and 2) uses something much closer to the correct formula (ie, no useless division by 1).

Categories