How can I get my function, which uses another function as argument to work?

Viewed 39

For an assignment I have to make a function that calculates the forward derivative of an input function and then make sure it works by running it on sin(x). I tried to make it like this:

import numpy as np
import matplotlib.pyplot as plt

def ForwardDer(f(x),h=0.1):
    FDer = (f(x*+h)-f(x*))/h
    return FDer

And to test this code I ran:

ExampleSin = ForwardDer(math.sin(5))
print(ExampleSin)

This gave me a syntax error so after some googling I adjusted my code to the following.

def ForwardDer(f,x*,h=0.1):
    FDer = (f(x*+h)-f(x*))/h
    return FDer

ExampleSin = ForwardDer(math.sin(),5)
print(ExampleSin)

This complains that math.sin has too few arguments but using (math.sin(5)) as an argument also doesn't work. Can anybody explain to me how I can succesfully call a function like this in another function? I really don't get it.

1 Answers

When you pass function, method, class or any other callable as argument, you don't want to call it with ().

Do not use * in variable name. It's special character.

It's also a good practice to name functions/methods/variables with snake_case and classes with CamelCase (Read: Naming Conventions).

I refactored your code a bit, check it out:

import math

def forward_der(func: callable, arg: float, h: float = 0.1) -> float:
    return (func(arg + h) - func(arg)) / h


example_sin = forward_der(math.sin, 5)
print(example_sin)

It prints to console:

0.33109592335406
Related