Menu - Help
(contains also links to help concerning Python and its modules)help(command)
or ? command
, for example help(print)
# Python knows correct operator precedence
1+2*3
7
# Parentheses can be used as necessary
(1+2)*3
9
# Power in Python: **
(1+2)**3
27
# Assignment operator in Python: = (equal sign)
a = 3
b = 4
# Calculate hypotenuse using Pythagorean theorem
c = (a**2 + b**2)**(1/2)
# Show the result
c
5.0
# Define function that calculates hypotenuse by means of Pythagorean theorem
def hypotenuse(a,b):
c = (a**2 + b**2)**(1/2)
return(c)
# Apply the above-defined function
c = hypotenuse(3,4)
# Show the result
c
5.0
# In order to use matematical functions, import them from math module
from math import sqrt,sin,pi
# Function sqrt = square root, like in most other programming languages
sqrt(9)
3.0
# Trigonometric functions work with radians
sin(0), sin(pi/2)
(0.0, 1.0)
# Logarithms
# (note: we can import more functions whenever needed
# (log = natural logarithm, log10 = common/decadic/decimal logarithm
from math import log,log10
sqrt(100), log(100), log10(100)
(10.0, 4.605170185988092, 2.0)
# List of all (public) functions in math module
# (the following code uses several Python tricks
# (you can ignore these tricks - just the output is important
import math
for func in math.__dir__():
if not(func.startswith('__')):
print(func, end=' ')
acos acosh asin asinh atan atan2 atanh ceil copysign cos cosh degrees dist erf erfc exp expm1 fabs factorial floor fmod frexp fsum gamma gcd hypot isclose isfinite isinf isnan isqrt lcm ldexp lgamma log log1p log10 log2 modf pow radians remainder sin sinh sqrt tan tanh trunc prod perm comb nextafter ulp pi e tau inf nan
# (0) Jupyter always shows just the last expression...
x = 10
x + 1
x + 2
12
# (1) ...but we can print more expressions separated by comma
x, x+1, x+2
(10, 11, 12)
# (2) Better printing => print() function
print('Hello!')
print('1st expression:', x+1)
print('2nd expression:', x+2)
Hello! 1st expression: 11 2nd expression: 12
# (3) Even better printing => print() with %-formatting
from math import pi,e
print('pi (default output) :', pi)
print('pi (formatted output): %.3f' % pi)
print('pi,e (four decimals) : %.4f, %.4f' % (pi,e))
pi (default output) : 3.141592653589793 pi (formatted output): 3.142 pi,e (four decimals) : 3.1416, 2.7183
# (4) Modern alternative to print() with %-formatting => formatted strings
print(f'pi (default output) : {pi}')
print(f'pi (formatted output): {pi:.3f}')
print(f'pi,e (four decimals) : {pi:.4f} {e:.4f}')
pi (default output) : 3.141592653589793 pi (formatted output): 3.142 pi,e (four decimals) : 3.1416 2.7183
# (5) A few notes about formatting:
# - the examples above = typical case = formatting of floating point numbers
# - more examples on www -> for example: GoogleSearch -> python print formatting
numpy
= for large data sets - more info: Jupyter - Menu - Help - Numpy referencemaptplotlib.pyplot
= for plotting - more info: Jupyter - Menu - Help - Matplotlib reference# Import modules for graphing
# (numpy = for large data sets, array/vector computing
# (matplotlib.pyplot = for ploting in Python
import numpy as np
import matplotlib.pyplot as plt
# 1) numpy: define X variable (as numpy array)
X = np.linspace(0,30,num=1001,endpoint=True)
# 2) numpy: define Y variable (as numpy array)
# Note: we use numpy functions, because...
# ...sin(x) works for scalars (but not for numpy arrays)
# ...np.sin(x) works for whole arrays (this is called array/vector computing)
Y = X + np.sin(X)
# 3) plot the result (using matplotlib.pyplot = plt)
plt.plot(X,Y)
plt.xlabel('x')
plt.ylabel('y = f(x)')
plt.grid()
plt.show()
# Supplement: print a few firs values of X,Y
# (just demo & check, not necessary for the graphing above, of course
print(np.round(X[:10],2))
print(np.round(Y[:10],2))
[0. 0.03 0.06 0.09 0.12 0.15 0.18 0.21 0.24 0.27] [0. 0.06 0.12 0.18 0.24 0.3 0.36 0.42 0.48 0.54]
# (1) Define X-variable for plotting = vector/array with more values
X = np.linspace(0,10,1001,endpoint=True)
# (2) Define Y-variables for plotting = functions of X
# (the functions must be numpy functions, which work with arrays
Y1 = np.sin(X)
Y2 = np.cos(X)
# (3) Plot two simple functions of X-variable
# (the functions have to be numpy functions
plt.plot(X,Y1, label='sine')
plt.plot(X,Y2, label='cosine')
plt.title('Demo: two functions in one graph')
plt.legend()
plt.grid()
plt.show()
sympy
= symbolic calculations - more info: Jupyter - Menu - Help - Sympy referencemath.sin(x) = sin(x)
works with scalars (single values)numpy.sin(x) = np.sin(x)
works with numpy arrays (used for plotting)sympy.sin(x) = sp.sin(x)
works for symbols (used in symbolic calculations)# 1) Import module for symbolic calculations
import sympy as sp
# 2) Initialize nice printing of symbolic expressions
sp.init_printing()
# 3) Define, which variables will behave like symbols
x,y = sp.symbols('x y')
# Short way
# (Note: equations are defined by sp.Eq
# (Thus: x**2 = 4 is written as sp.Eq(x**2,4)
# (Reason: equal sign (=) is for assignments, not for equations
sp.solve(sp.Eq(x**2,4))
# Longer, step-by-step way with nicer output
# 0) Define ONE equation to solve
e1 = sp.Eq(x**2,4)
# 1) Display the equation
print('Equation to solve:')
display(e1)
# 2) Solve the equation
solution = sp.solve(e1,x)
# 3) Display the solution
print('Solution of the equation:')
display(solution)
Equation to solve:
Solution of the equation:
# Short way
# (Note: for multiple equations, this may be difficult to read
# (Conclusion: it is probably better to use the step-by-step way below
sp.solve( [sp.Eq(x+y,3), sp.Eq(x-y,1)] , [x, y] )
# Longer, step-by-step way with nicer output
# 0) Define set of TWO equations to solve
e1 = sp.Eq(x+y,3)
e2 = sp.Eq(x-y,1)
# 1) Display the equations
print('Set of two equations to solve:')
display(e1,e2)
# 2) Solve the set of equations
solution = sp.solve([e1,e2],[x,y])
# 3) Display the solution
print('Solution of the equations:')
display(solution)
Set of two equations to solve:
Solution of the equations:
# Short way
sp.limit(1/x,x,0,dir='+')
# Longer, step-by-step way with better output
# 0) Define limit
e1 = sp.Limit(1/x,x,0,dir='+')
# 1) Calculate limit
e2 = e1.doit()
# 2) Display the result
e3 = sp.Eq(e1,e2)
display(e3)
# Short way
sp.diff(sp.sin(x), x)
# Longer, step-by-step way with better output
# 0) Define derivative
e1 = sp.Derivative(sp.sin(x), x)
# 1) Calculate derivative
e2 = e1.doit()
# 2) Display the result
e3 = sp.Eq(e1,e2)
display(e3)
# Short way
sp.integrate(x*sp.exp(x), x)
# Longer, step-by-step way with better output
# 0) Define integral
e1 = sp.Integral(x*sp.exp(x),x)
# 1) Calculate integral
e2 = e1.doit()
# 2) Display the result
e3 = sp.Eq(e1,e2)
display(e3)
# (1) Define function for test of Taylor series calculations
e1 = sp.sin(x)
# ...create Taylor series up to n=5
e2 = e1.series(x,0,10)
# ...display the result in the form of equation
e3 = sp.Eq(e1,e2)
display(e3)
# (2) Draw result graphically
# (we need several tricks
# (you can take the code below as a template
# (or you can learn more: Google - Search - Sympy - lambdify...
# Trick 1: get LHS of eq3 without the last member
# (reason: the last member represents error, not real number
e2 = e2.removeO()
display(e2)
# Trick 2: convert sympy function to numpy function
# (reason: sympy functions are for symbolic calculations, numpy functions for plotting
my_function = sp.lambdify(x,e2,'numpy')
# Trick 3: now we can define X-values and Y-values for numpy
# (note: my_function is a numpy function that works on numpy arrays
X = np.linspace(-10,10,2001,endpoint=True)
Y1 = np.sin(X)
Y2 = my_function(X)
# Plot the results
# (no further tricks here: plotting like in section 2 above
plt.title('Taylor expansion of sin(x)')
plt.plot(X,Y1, 'y-', label='sin(x)')
plt.plot(X,Y2, 'r-', label='Taylor(n=10)')
plt.ylim(-5,5)
plt.legend()
plt.grid()
plt.show()
# Super-brief revision
# 1) Standard equations contain basic operations (+-*/) and specific functions (sin(x))
# * Solution of standard equations -> numbers
# * Example: x + 2 = 5 -> solution: x = 3
# 2) Differential equations contain general functions (f(x)) and their derivatives (df/dx)
# * Solution of differential equations -> functions
# * Example: df/dx = 2x -> solution: f(x) = x**2
# Defining and solving the simple example above
# (i.e. define and solve equation: df/dx = 2x
# (1) Define general sympy function
f = sp.symbols('f', cls=sp.Function)
# (2) Define and print derivative of this general function
# (demo & check that the general f(x) works as expected
# (moreover, symbol df can be used in definition below
df = f(x).diff(x)
display(df)
# (3) Define the differential equation
# (like algebraic equations above, just using the f, df...
e1 = sp.Eq(df,2*x)
display(e1)
# (4) Solve the differential equation
# (like algebraic equations above, just solve -> dsolve
sp.dsolve(e1,f(x))
# (5) Conclusions
# * SymPy can solve also differential equations
# (i.e. common types of differential equations
# * constant C1 is the solution above is correct:
# d(x**2 + C1)/dx = d(x**2)/dx = 2x
# * more about differential equations:
# https://en.wikipedia.org/wiki/Differential_equation
# * more about differential equations in SymPy:
# https://docs.sympy.org/latest/tutorial/solvers.html