O'Reilly logo

NumPy Cookbook - Second Edition by Ivan Idris

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Calling C functions

We can call C functions from Cython. In this example, we call the C log() function. This function works on a single number only. Remember that the NumPy log() function can also work with arrays. We will compute the so-called log returns of stock prices.

How to do it...

We start by writing some Cython code:

  1. First, import the C log() function from the libc namespace. Then, apply this function to numbers in a for loop. Finally, use the NumPy diff() function to get the first-order difference between the log values in the second step:
    from libc.math cimport log
    import numpy as np
    
    def logrets(numbers):
       logs = [log(x) for x in numbers] 
       return np.diff(logs)

    Building has been covered in the previous recipes. We only need to change some values ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required