In [1]:
%load_ext cython

Demonstration of integer overflow


In [4]:
%%cython
# cython: language_level=3

# int would overflow, but unsigned int won't
cpdef f():
    cdef int i  # Max value: 2147483647
    for i in range(2147483645, 2147483650):
        print(i)

In [5]:
f()


2147483645
2147483646
2147483647
-2147483648
-2147483647

In [6]:
%%cython
# cython: language_level=3

# int would overflow, but unsigned int won't
cpdef f():
    cdef unsigned int i  # Max value: 2147483647
    for i in range(2147483645, 2147483650):
        print(i)

In [7]:
f()


2147483645
2147483646
2147483647
2147483648
2147483649

Demonstration of floating-point error

1) Loss of precision


In [8]:
%%cython
# cython: language_level=3

# float would lose precision, but double won't
cpdef g():
    cdef float x, y, z
    x = 1
    y = 1e-15
    z = x + y
    print('x =     ', x)
    print('y =     ', y)
    print('x + y = ', z)

In [9]:
g()


x =      1.0
y =      1.0000000036274937e-15
x + y =  1.0

In [10]:
%%cython
# cython: language_level=3

# float would lose precision, but double won't
cpdef g():
    cdef double x, y, z
    x = 1
    y = 1e-15
    z = x + y
    print('x =     ', x)
    print('y =     ', y)
    print('x + y = ', z)

In [11]:
g()


x =      1.0
y =      1e-15
x + y =  1.000000000000001

2) Misrepresentation


In [12]:
%%cython
# cython: language_level=3

cpdef h():
    cdef float x = 0.1
    print('x =     ', x)

In [13]:
h()


x =      0.10000000149011612

In [14]:
%%cython
# cython: language_level=3

cpdef h():
    cdef double x = 0.1
    print('x =     ', x)

In [15]:
h()


x =      0.1

In [ ]: