fastinvsqrt
===========

This folder includes an example to demonstrate two aspects:
	1. How a C function can be wrapped via Cython to be accessible in Python
	2. How to compile Cython code into a Python module so that it can be used as a regular module in other parts of your code


Background
----------
We are using the C implementation of the so-called fast inverse square root function. This is a function to calculate $1/\sqrt{x}$ of a value very fast. This function is helpful when normalising vectors to be of unit-length.
One particular application is in rendering of lighting and shading effects in computer graphics.

You can find more details in this article:
https://en.wikipedia.org/wiki/Fast_inverse_square_root

c_func.c contains the implementation in C called fast_inv_sqrt.

Wrapping
--------
The Cython file fis.pyx wraps the fast_inv_sqrt function from c_func.c and creates two python exposed functions
	- py_fis: that just wraps the fast_inv_sqrt function
	- norm_vector: 
		- that takes a list of numbers assumed to be the coordinates of a vector
		- calculating the squared length of the vector
		- calculating the its inverse square root 
		- multiply this factor with each coordinate of the vector to normalise it

Compiling
---------
The Cython file fis.pxy can be compiled by calling the setup.py script with the command

$ python setup.py build_ext --inplace

This creates a shared object called fis.*.so (* represents a part of the file name that varies with the operating system and Python version used)

There is for illustration purposes also a small C script in run.c that uses the fast inverse square root function in c_func.c directly.

Both elements, the Cython file and the C script, can be compiled via the Makefile

$ make

Usage
-----
The shared object can be imported into Python code via
>>> import fis
And then the two functions py_fis and norm_vector can be used.

To run the C executable (resulting from the compilation of the C script run.c) just call in the terminal
$ ./run



	