Calculus using Functional Python

Photo by Jafet Reyes on Unsplash

The aim this piece is to demonstrate some concepts of functional programming in Python, let’s dive-in!

Part Derivative:

The following function calculates the slope on a non-linear line.

https://en.wikipedia.org/wiki/derivative

Now let rewrite the code in Python.

This function is equivalent to the prior:

Functions in Python are first-class functions, which means that you can treat them as variables.

Note that the value 1e-3 (0.001) is the limit when h approaches zero (h → 0).

Now we use a partial function:

Partial functions allow us to pass fewer arguments to multiple arguments function.

In this example, we create a partial function from the function derivative, and its first argument (the sine function), leaving x for call time.

Correct! since the derivative of sin is cos.

Let’s try x²

As you can see, we passed a lambda calculus expression because our function derivative expects a function.

Ten is the correct answer since the derivative of is 2 * x.

Try to plug your function.

Part Integral:

We are going to use algebra to tackle the integral function.

This function has four important arguments; the range from a to b, the steps, and the input function.

https://en.wikipedia.org/wiki/integral

In calculus, we find the integral of (x³ / 3) to find the solution.
With algebra, we stack multiple rectangles together to find the solution.

Using algebra:

Using calculus:

The algebra method is approaching the correct solution, albeit it requires a lot of calculation than you transistors!

Let’s define the function:

Note that AUC stands for the area under the curve.

Integral is a high-order function, which means that it can take a function as an argument or return a function.

Now, let’s use partial again:

if we pass our partial function with the limits a and b, we get:

Hooray!

Part Integral++:

Another approach is using closures:

The integral function will return the function g.

The function g holds the value of delta way after the execution of the outer function; this is closure.

Next, we pass a complex function and the number of steps delta.

Passing the limits:

That’s correct!

Final thoughts:

Functional programming has many elegant concepts, some concepts covered:

  • first-class functions
  • partial functions
  • lambda calculus
  • high-order functions
  • closures

You can find more examples on the GitHub link with additional functional techniques.

https://github.com/booletic/medium/blob/34b60709ce0bd0d657e1e2c88a58125a19b6ee91/calculus.ipynb

Programming and Statistics for now!