Skip to content

Instantly share code, notes, and snippets.

@javipus
Created December 21, 2018 13:17
Show Gist options
  • Save javipus/2681d13d2668be23781b062d8aa629fb to your computer and use it in GitHub Desktop.
Save javipus/2681d13d2668be23781b062d8aa629fb to your computer and use it in GitHub Desktop.
"""
I never cared about my machine's epsilon until I did.
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Machine precision - in bits
prec = -int(np.log2(np.finfo(float).eps))
# Count up to
B0 = 11
# Add/subtract up to
B1 = 20
# 2^j only shifted to the decimal place: ..., .8, .16, .32, .64, .128, ...
good = lambda b0: list(map(lambda x: x/10**(int(np.log10(x)+1)), [2**j for j in range(b0)]))
# x -> x + 2**b -> x - 2**b != x -- boom!
bad = lambda b0, b1: [list(map(lambda x: x-2**j, map(lambda x: x+2**j, good(b0)))) for j in range(b1)]
# Total error
err = lambda b0, b1: np.array(bad(b0,b1))-np.array([good(b0)]*b1)
d = pd.DataFrame(np.array(np.log2(abs(err(B0,B1))))).T
# Plot it
[plt.scatter(d.columns, row, marker = 'o', color = 'k') for _, row in d.iterrows()]
plt.plot(range(B1), np.array(range(B1))-prec, ls = '--')
plt.xlabel('Extra significant bits')
plt.ylabel('Effective machine epsilon')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment