Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematical expression as argument to function?

I'm very much a beginner, so please be gentle.

I am tinkering with some Python exercises, and I have code looking like this.

def newton(x0, Tol):
    def F(x):
        return (x**3)+898
    def dF(x):
        return 3*x**2
    x=[x0]
    for n in range(400):
        x.append(x[n]-(F(x[n]))/dF(x[n]))
        if abs((x[n+1])-(x[n]))<Tol:
            conv='Converge'
            print n
            break
    if abs((x[n+1])-(x[n]))>=Tol:
        conv='No converge'
    return x[n+1], conv

I define a function F(x) and its derivative dF(x) and add values to a list x.

The task is to check if the series converge or not, which I think I have succeeded with.

But the question I have is regarding having the functions (x**3)+898 and 3*x**2 as arguments to the function Newton.

I imagined it would be something like this

def newton(f, df, x0, Tol):
    def F(x):
        return f
    def dF(x):
        return df
    *calculations*
    return x[n+1], conv

And you would call it with

newton((x**3)+898, 3*x**2, x0=something, Tol=something)

So that the functions F(x) and dF(x) are defined in the process.

However, x is not defined so it does not work.

Note that having f and df as parameters of 'newton' is required in the excercise.

How would you go about solving this?

Thanks.

like image 658
user2298619 Avatar asked Jan 13 '23 14:01

user2298619


2 Answers

You can use lambdas, which are basically simple functions.

You would call it like this:

newton(lambda x: (x**3)+898, lambda x: 3*x**2, x0=something, Tol=something)

This would be the same as doing something like this:

def f1(x):
    return (x**3)+898
def f2(x):
    return 3*x**2
newton(f1, f2, x0=something, Tol=something)

The only difference is that you don't "give the lambda a name", ie assign it to a variable. This is handy for functions you only need to use once, especially as key arguments to functions like sorted and max.

like image 74
Volatility Avatar answered Jan 21 '23 12:01

Volatility


Use lambda:

newton(lambda x: (x**3)+898, lambda x: 3*x**2, x0=something, Tol=something)
like image 45
kalgasnik Avatar answered Jan 21 '23 12:01

kalgasnik