Short reminders about decimal and binary number systems
The number in decimal number system:
1234=1β103+2β102+3β101+4β100
The number in binary number system:
1011=1β23+0β22+1β21+1β20
Table with decimal to binary map
Now, the floating-point numbers are represented in computer hardware as base 2 (binary) fractions.
For example this is decimal fraction:
0.125 --> 1/10 + 2/100 + 5/1000
In binary form 0.125 is 0.001.
And binary fraction for this number would be:
0.001 -> 0/2 + 0/4 + 1/8
Python only prints a decimal approximation to the true decimal value of the binary approximation stored by the machine. If Python were to print the true decimal value of the binary approximation stored for 0.1, it would have to display
To set human-friendly numbers β convert string with number to Decimal :
πͺ Code:
Decimal('0.1')+Decimal('0.2')
π Output:
Decimal('0.3')
Complex calculations
Usual float-point calculations are fast but (as we just saw not accurate). So what if you need to be precise and fast? Obvious answer - "use Decimal" is not that good because Decimal is slow (in Python3 it was greatly optimized bu still it is not super fast). So consider this when doing heavy calculations. For this it's better to either use PyPy interpreter or write this as separate C module.
πͺ Code:
%%timeitfor x inrange(1000, 1000000):10/ x
π Output:
97.8 ms Β± 4.27 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each)
πͺ Code:
%%timeitfor x inrange(1000, 1000000):10/Decimal(x)
π Output:
607 ms Β± 7.19 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)
Scientific calculations
There are two main modules - very big and omnipotent for this:
NumPy
Fast and efficient array implementation
Handy for building plot, graphs, hystograms, 3D-graphs etc.
SciPy
Social data analysis
Tough mathematical terms and stuff
Physics, chemistry modelling
πͺ Code:
%matplotlib inlineimport numpy as npimport matplotlib.pyplot as plt# Build a vector of 10000 normal deviates with variance 0.5^2 and mean 2mu, sigma =1.5,0.7v = np.random.normal(mu,sigma, 3700)# Plot a normalized histogram with 50 binsplt.hist(v, bins=80, density=1.3)# matplotlib version (plot)plt.show()