Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.


Hello! Friend!!!

Thank you very much for reading haihong’s article, if there are any mistakes in the article, please point out ~


Self-introduction ଘ(੭, ᵕ)੭

Nickname: Haihong

Tag: programmer monkey | C++ contestant | student

Introduction: because of C language to get acquainted with programming, then transferred to the computer major, had the honor to get some national awards, provincial awards… Has been confirmed. Currently learning C++/Linux/Python

Learning experience: solid foundation + more notes + more code + more thinking + learn English well!

Little White stage of learning Python

The article is only used as my own study notes for the establishment of knowledge system and review

The problem is not to learn one more question to understand one more question

Know what is, know why!

1. Recursive relationship – yeast growth model

The key of difference equation modeling is how to get the relationship between the NTH group of data and the NTH +1 group of data

As you can see here, when we grow bacteria in culture, they usually go through these four phases.

This model builds a rough model for the first three periods:

  • adjustment
  • Logarithmic phase
  • plateau

Plot based on existing data:

import matplotlib.pyplot as plt 
time = [i for i in range(0.19)] 
number = [] 
plt.title('Relationship between time and number')# create title
plt.xlabel('time')# X axis labels
plt.ylabel('number')# Y axis labels
plt.plot(time,number)# drawing show
Copy the code


There is a law of yeast population growth: when certain resources can only support a maximum population, but cannot support unlimited population growth, the population growth rate will slow down.

  • The difference between the values of the two observation points, △ P, represents the growth rate
  • △ P is related to the current population, the larger the population, the faster the growth rate
  • △ P is also related to the amount of remaining unallocated resources. The more resources, the faster the growth rate
  • Then the remaining resources were represented by the difference between the number of limiting groups and the number of existing populations

Model: Δ p = pn + 1 – pn = k (665 – pn) pn \ Delta p = p_ {n + 1} – p_n = k (665 – p_n) p_n Δ p = pn + 1 – pn = k (665 – pn) pn

Then calculate the coefficient k of the model expression (given pn, δ pp_n, \Delta PPN, δ P). When the formula is fitted as a quadratic curve:

import numpy as np
import matplotlib.pylab as plt
p_n = []
delta_p = []

poly = np.polyfit(p_n, delta_p, 2)
z = np.polyval(poly,p_n)

plt.plot(p_n, z)
# [-8.01975671e-04  5.16054679e-01  6.41123361e+00]
# k = -8.01975671e-04
Copy the code

The resultsWhen the asA curveWhen we fit

665 minus p sub n times p sub n is a function of one order

import numpy as np
import matplotlib.pylab as plt
p_n = []
delta_p = []

p_n = np.array(p_n)
x= (665 - p_n) * p_n

ploy = np.polyfit(x,delta_p,1)
z = np.polyval(ploy,x)


# [0.00081448 0.30791574]
# k = 0.00081448
Copy the code

The results

Prediction curve:

import matplotlib.pyplot as plt 
p0 = 9.6 
p_list = [] 
for i in range(20): 
    p0 = 0.00081448* (665-p0)*p0+p0 
Copy the code

Running results:

2 shows the differential – heat conduction equation

One-dimensional heat conduction equation is:

Where, k is the heat conduction coefficient, Equation 2 is the initial value condition of the equation, and Equation 3 and 4 are the boundary value condition. The heat conduction equation is as follows:

Plot the initial conditional function (second formula)

import numpy as np
import matplotlib.pylab as plt

x = np.linspace(0.1.100)
y = 4 * x * (1 - x)

Copy the code

The resultsNote: CAL library is not installed, the following code is not run, I wrote it according to PPT (installed for one day, but the operation keeps reporting errors)

N = 25 
M = 2500 
T = 1.0 
X = 1.0 
xArray = np.linspace( 
yArray = map(initialCondition, xArray) 
starValues = yArray 
U = np.zeros((N+1,M+1)) 
for k in range(0,N): 
    for j in range(1,N): 
        U[j][k+1]=rho*U[j-1][k]+ (1.-2*rho)*U[j][k]+ rho*U[j+1][k] 
    U[0][k+1] =0. 
    U[N][k+1] =0. 
pylab.plot(xArray, U[:,0]) 
pylab.plot(xArray, U[:,int(0.10/dt)]) 
pylab.plot(xArray, U[:,int(0.20/dt)]) 
pylab.plot(xArray, U[:,int(0.50/ dt)]) pylab. Xlabel ($x $, fontsize =15) pylab. Ylabel (' $r U $' (\ dot, \ tau), fontsize =15Pylab.title (u 'One-dimensional heat conduction equation', fontProperties =font) Pylab.legend ([r '$\tau=0.$', 'r' $\ tau =0.10$', 'r' $\ tau =0.20$', 'r' $\ tau =0.50Fontsize = $']15)
Copy the code

Three-dimensional view of the overall heat conduction process:

tArray = np.linspace(
xGride, tGride = np.meshgrid(xArray, tArray) 
from mpl_toolkits.mplot3d import Axes3D 
from matplotlib import cm 
fig = pylab.figure(figsize=(16.10)) 
ax = fig.add_subplot(1.1.1,projection= '3d') surface = ax.plot_surface(xGride, tGride, U[:,:int(0.2/dt)+1]. J T, cmap = cm. Coolwarm) ax. Set_xlabel (" $$" x, fontdict = {" size ":18"$}) ax. Set_ylabel (r \ tau $", fontdict = {" size" :18}) ax. Set_zlabel (r $U $", "fontdict = {" size" :18}) ax.set_title(u "Heat conduction equation $u_\\tau = u_{xx}$", fontproperties=font) colorbar(surface, shrink=0.75)
Copy the code

3. Markov Chain – Election voting prediction

A Markov chain is a process consisting of a series of events with the following properties:

  • An event has finitely many outcomes, called states, and the process is always one of these states;
  • At each stage or period of the process, a particular result may be transferred from its present state to any state, or remain unchanged;
  • The probability of moving from one state to another at each stage is represented by a transition matrix with elements in each row between 0 and 1, and the sum of each row is 1.

Taking the American election as an example, the historical data of the past ten elections were obtained first, and then the transfer matrix of voter intentions was obtained according to the historical data.

Constructing the difference equation:

Thus, the long-term trend of voters’ voting intentions can be predicted by solving the difference equations

import matplotlib.pyplot as plt 
RLIST = [0.33333] 
DLIST = [0.33333] 
ILIST = [0.33333] 
for i in range(40): 
    R = RLIST[i]*0.75+DLIST[i]*0.20+ILIST[i]*0.40 
    D = RLIST[i]*0.05+DLIST[i]*0.60+ILIST[i]*0.20 
    I = RLIST[i]*0.20+DLIST[i]*0.20+ILIST[i]*0.40 
plt.ylabel('Voting percent')
plt.annotate('DemocraticParty',xy = (5.0.2)) 
plt.annotate('RepublicanParty',xy = (5.0.5)) 
plt.annotate('IndependentCandidate',xy = (5.0.25)) 
Copy the code

The results

The resulting long-term trend is:

  • Fifty-six percent voted Republican
  • Nineteen percent voted Democratic
  • Twenty-five percent voted for independent candidates

This problem can also be solved by using the C-K equation

import numpy as np
a = np.array([[], [], []])
p = np.mat(a)
for i in range(40):
    p = p*p   
Copy the code

Running results:


Source of learning: STATION B and its classroom PPT, the code is reproduced

The essay is just a study note, recording a process from 0 to 1

Hope to help you, if there is a mistake welcome small partners to correct ~