# biscetion
""" root = bisection(f,x1,x2,switch=0,tol=1.0e-9).
Finds a root of f(x) = 0 by bisection.
The root must be bracketed in (x1,x2).
Setting switch = 1 returns root = None if
f(x) increases upon bisection.
"""
import math
from numpy import sign
def bisection(f,x1,x2,switch=1,tol=1.0e-9):
f1 = f(x1)
if f1 == 0.0: return x1
f2 = f(x2)
if f2 == 0.0: return x2
if sign(f1) == sign(f2):
print('Root is not bracketed')
n = int(math.ceil(math.log(abs(x2 - x1)/tol)/math.log(2.0)))
for i in range(n):
x3 = 0.5*(x1 + x2); f3 = f(x3)
if (switch == 1) and (abs(f3) > abs(f1)) \
and (abs(f3) > abs(f2)):
return None
if f3 == 0.0: return x3
if sign(f2)!= sign(f3): x1 = x3; f1 = f3
else: x2 = x3; f2 = f3
return (x1 + x2)/2.0
""""//////////////////////////////////////////////////////////////////"""
# run_kut4
""" X,Y = integrate(F,x,y,xStop,h).
4th-order Runge-Kutta method for solving the
initail value problem {y}' = {F(x,{y})},where
{y} = {y[0],y[1],...,y[n-1]}.
x,y = initial conditions
xStop = terminal value of x
h =increment of x used in integration
F =user - supplied function that returns the
array F(x,y) = {y'[0],y'[1],...,y'[n-1]}.
"""
import numpy as np
def integrate(F,x,y,xStop,h):
def run_kut4(F,x,y,h):
K0 = h*F(x,y)
K1 = h*F(x + h/2.0, y + K0/2.0)
K2 = h*F(x + h/2.0, y + K1/2.0)
K3 = h*F(x + h, y + K2)
return (K0 + 2.0*K1 + 2.0*K2 + K3)/6.0
X = []
Y = []
X.append(x)
Y.append(y)
while x < xStop:
h = min(h,xStop - x)
y = y + run_kut4(F,x,y,h)
x = x + h
X.append(x)
Y.append(y)
return np.array(X), np.array(Y)
""""//////////////////////////////////////////////////////////////////"""
## printsSoln
""" printSoln(X,Y,freq).
Prints X and Y returner from the differential
equation solves using printout frequency 'freq'.
freq = n prints every nth step.
freq = 0 prints inital and final values only.
"""
def printSoln(X,Y,freq):
def printHead(n):
print('\n{:>13}'.format('x'),end=" ")
for i in range(n):
print('{}{}{}{}'.format(' '*(9),'y[',i,']'),end=" ")
print()
def printLine(x,y,n):
print("{:13.4}".format(x),end=" ")
for i in range(n):
print("{:13.4f}".format(y[i]),end=" ")
print()
m = len(Y)
try: n = len(Y[0])
except TypeError: n = 1
if freq == 0: freq = m
printHead(n)
for i in range(0,m,freq):
printLine(X[i],Y[i],n)
if i != m - 1: printLine(X[m - 1],Y[m - 1],n)
""""//////////////////////////////////////////////////////////////////"""
"""
solve the differential equation
y''' + yy" + B(1 - y'^2)= 0 y(0) = 0 y'(0) = 0,y'(+inf) = 0
B = [0,0.2,0.4,0.6,0.8,1.0,-0.1,-0.15]
"""
import matplotlib.pyplot as plt
import time
start = time.clock()
def initCond(u): #Init. values of [y.y']; use 'u' if unkown
return np.array([0.0,0.0,u])
def r(u): # Boundart condition resdiual
X,Y = integrate(F,xStart,initCond(u),xStop,h)
y = Y[len(Y) - 1]
r = y[1] - 1.0
return r
def F(x,y): # Third-order differential equations
F = np.zeros(3)
F[0] = y[1]
F[1] = y[2]
F[2] = -y[0]*y[2] - (1 - y[1]*y[1])
return F
xStart = 0.0 # Start of integration
xStop = 5 # End of integraiton
u1 = 1.0 # 1st trial value of unknown init. cond.
u2 = 2.0 # 2nd trial value of unknown init. cond.
h = 0.1 # Step size
freq = 2 # Printout frequency
u = bisection(r,u1,u2,tol = 1.0e-9) #Comput the correct initial condition
X,Y = integrate(F,xStart,initCond(u),xStop,h)
print(initCond(u))
printSoln(X,Y,freq)
end = time.clock()
print('duration =',end - start)
plt.plot(X, Y[:,0], label='y')
plt.plot(X, Y[:,1], label='y\'')
plt.legend()
plt.show()
Не могли бы вы показать код, ваши испытания и определить проблемы, которые встречаются с –
printSoln представляет собой форматированный печать funciton.I konw мой код неправильно, я новичок в Python – Smithermin
И в чем проблема с этим кодом? Вы пробовали это шаг за шагом, чтобы увидеть, где он начинает отклоняться от ожидаемых результатов? – deceze