Home » programming » Floating number operations

Floating number operations

Because of how floating numbers work, we can have some surprising results. Can you guess what the next snippet is printing?

from __future__ import print_function

print("The answer is:", int((0.1 * 3 - 0.3) ** -0.1))

Exercise for the reader.

Can you use the fact that:

import numpy as np

v = np.spacing(np.single()) / 2
s = 1.0
s + v   # prints 1.0
s = 0.0
s + v   # prints > 0.0

To make a statement that 1.0 + 1.0 = 2.0 sometimes while 1.0 + 1.0 = 1.0 some other times?

Hint: Use a loop.

If someone requests it, I will post the solution. Credits to Prof. Gallopoulos for this second exercise.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: