Textbook example - Result is off on Linux with distutils and cythonize

36 views
Skip to first unread message

Vraj Mohan

unread,
Aug 15, 2016, 4:11:07 AM8/15/16
to cython-users
I am new to Cython.

When I tried the Fibonacci example from Kurt Smith's book https://library.oreilly.com/book/0636920033431/cython/toc.xhtml, I found the result is off for fib(37).

Here's the Cython code - fib.pyx:

def fib(int n):
    cdef int i
    cdef double a=0.0, b=1.0
    for i in range(n):
        a, b = a + b, a
    return a

Here's test code - test_fib.py:

from fib import fib

for i in range(35, 38):
     print(fib(i))
assert fib(35) + fib(36) == fib(37)

The output is:
9227465.0
14930352.0
24157816.0
Traceback (most recent call last):
  File "test_fib.py", line 7, in <module>
    assert fib(35) + fib(36) == fib(37)
AssertionError


This issue happens with:
1. distutils and cythonize
2. pyximport

This works correctly with:
1. Interactive Cython with IPython’s %%cython Magic
2. On OS X (using distutils and cythonize)


Jeroen Demeyer

unread,
Aug 15, 2016, 4:14:03 PM8/15/16
to cython...@googlegroups.com
On 2016-08-14 19:05, Vraj Mohan wrote:
> I am new to Cython.
>
> When I tried the Fibonacci example from Kurt Smith's book
> https://library.oreilly.com/book/0636920033431/cython/toc.xhtml, I found
> the result is off for fib(37).

Works for me. No idea what could be wrong. Maybe a broken C compiler? A
hardware problem?

Robert Bradshaw

unread,
Aug 15, 2016, 9:25:02 PM8/15/16
to cython...@googlegroups.com
I can't reproduce this either. Could you give exact details on the
failing system? Do you have a strange setup of some sort? Could you
print a and b in the loop?

Something's really messed up if your CPU gives 24157816.0 for
9227465.0 + 14930352.0.

Jeroen Demeyer

unread,
Aug 16, 2016, 3:28:27 AM8/16/16
to cython...@googlegroups.com
Here is a guess: the output is what you get when using single-precision
floats (they have 24 bits of precision, so 24157817.0 gets rounded to
24157816.0). So it seems that something (most likely some library) has
put your CPU in single-precision mode.

Vraj Mohan

unread,
Aug 16, 2016, 8:25:59 AM8/16/16
to cython-users
The example works correctly on a different system with the identical Linux dist - Ubuntu 16.04.1.

The build environment on my original system must be borked.

Thank you for investigating this, and sorry to waste your time.

--Vraj
Reply all
Reply to author
Forward
0 new messages