Python计算方程(python计算方程系数)

http://www.itjxue.com  2023-03-24 21:11  来源:未知  点击次数: 

python求一元二次方程的根的代码

以下是Python代码,用于计算一元二次方程的根:

import math

a = float(input("请输入二次项系数a:"))

b = float(input("请输入一次项系数b:"))

c = float(input("请输入常数项c:"))

delta = b**2 - 4*a*c

if delta 0:

print("该方程无实数根")

elif delta == 0:

x = -b / (2*a)

print("该方程有一个实数根:x =", x)

else:

x1 = (-b + math.sqrt(delta)) / (2*a)

x2 = (-b - math.sqrt(delta)) / (2*a)

print("该方程有两个实数根:x1 =", x1, ", x2 =", x2)

在这个程序中,用户需要输入方程的二次项系数、一次项系数和常数项。程序使用math模块中的sqrt函数来计算方程的判别式delta,然后根据delta的值判断方程的根的情况。如果delta小于0,则方程没有实数根;如果delta等于0,则方程有一个实数根;如果delta大于0,则方程有两个实数根。

程序输出方程的根,如果方程没有实数根,则输出相应的提示。

请注意,在输入系数时,要确保输入的是浮点数,否则可能会导致程序出错。

如何使用python计算常微分方程?

常用形式

odeint(func, y0, t,args,Dfun)

一般这种形式就够用了。

下面是官方的例子,求解的是

D(D(y1))-t*y1=0

为了方便,采取D=d/dt。如果我们令初值

y1(0) = 1.0/3**(2.0/3.0)/gamma(2.0/3.0)

D(y1)(0) = -1.0/3**(1.0/3.0)/gamma(1.0/3.0)

这个微分方程的解y1=airy(t)。

令D(y1)=y0,就有这个常微分方程组。

D(y0)=t*y1

D(y1)=y0

Python求解该微分方程。

from scipy.integrate import odeint

from scipy.special import gamma, airy

y1_0 = 1.0/3**(2.0/3.0)/gamma(2.0/3.0)

y0_0 = -1.0/3**(1.0/3.0)/gamma(1.0/3.0)

y0 = [y0_0, y1_0]

def func(y, t):

... return [t*y[1],y[0]]

def gradient(y,t):

... return [[0,t],[1,0]]

x = arange(0,4.0, 0.01)

t = x

ychk = airy(x)[0]

y = odeint(func, y0, t)

y2 = odeint(func, y0, t, Dfun=gradient)

print ychk[:36:6]

[ 0.355028 0.339511 0.324068 0.308763 0.293658 0.278806]

print y[:36:6,1]

[ 0.355028 0.339511 0.324067 0.308763 0.293658 0.278806]

print y2[:36:6,1]

[ 0.355028 0.339511 0.324067 0.308763 0.293658 0.278806]

得到的解与精确值相比,误差相当小。

=======================================================================================================

args是额外的参数。

用法请参看下面的例子。这是一个洛仑兹曲线的求解,并且用matplotlib绘出空间曲线图。(来自《python科学计算》)

from scipy.integrate import odeint

import numpy as np

def lorenz(w, t, p, r, b):

# 给出位置矢量w,和三个参数p, r, b 计算出

# dx/dt, dy/dt, dz/dt 的值

x, y, z = w

# 直接与lorenz 的计算公式对应

return np.array([p*(y-x), x*(r-z)-y, x*y-b*z])

t = np.arange(0, 30, 0.01) # 创建时间点

# 调用ode 对lorenz 进行求解, 用两个不同的初始值

track1 = odeint(lorenz, (0.0, 1.00, 0.0), t, args=(10.0, 28.0, 3.0))

track2 = odeint(lorenz, (0.0, 1.01, 0.0), t, args=(10.0, 28.0, 3.0))

# 绘图

from mpl_toolkits.mplot3d import Axes3D

import matplotlib.pyplot as plt

fig = plt.figure()

ax = Axes3D(fig)

ax.plot(track1[:,0], track1[:,1], track1[:,2])

ax.plot(track2[:,0], track2[:,1], track2[:,2])

plt.show()

===========================================================================

scipy.integrate.odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0, ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0, hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12, mxords=5, printmessg=0)

计算常微分方程(组)

使用 FORTRAN库odepack中的lsoda解常微分方程。这个函数一般求解初值问题。

参数:

func : callable(y, t0, ...) 计算y在t0 处的导数。

y0 : 数组 y的初值条件(可以是矢量)

t : 数组 为求出y,这是一个时间点的序列。初值点应该是这个序列的第一个元素。

args : 元组 func的额外参数

Dfun : callable(y, t0, ...) 函数的梯度(Jacobian)。即雅可比多项式。

col_deriv : boolean. True,Dfun定义列向导数(更快),否则Dfun会定义横排导数

full_output : boolean 可选输出,如果为True 则返回一个字典,作为第二输出。

printmessg : boolean 是否打印convergence 消息。

返回: y : array, shape (len(y0), len(t))

数组,包含y值,每一个对应于时间序列中的t。初值y0 在第一排。

infodict : 字典,只有full_output == True 时,才会返回。

字典包含额为的输出信息。

键值:

‘hu’ vector of step sizes successfully used for each time step.

‘tcur’ vector with the value of t reached for each time step. (will always be at least as large as the input times).

‘tolsf’ vector of tolerance scale factors, greater than 1.0, computed when a request for too much accuracy was detected.

‘tsw’ value of t at the time of the last method switch (given for each time step)

‘nst’ cumulative number of time steps

‘nfe’ cumulative number of function evaluations for each time step

‘nje’ cumulative number of jacobian evaluations for each time step

‘nqu’ a vector of method orders for each successful step.

‘imxer’index of the component of largest magnitude in the weighted local error vector (e / ewt) on an error return, -1 otherwise.

‘lenrw’ the length of the double work array required.

‘leniw’ the length of integer work array required.

‘mused’a vector of method indicators for each successful time step: 1: adams (nonstiff), 2: bdf (stiff)

其他参数,官方网站和文档都没有明确说明。相关的资料,暂时也找不到。

利用Python语言计算方程的根

import math

def erfenfa(function, a, b): #定义函数,利用二分法求方程的根,function为具体方程,a,b为根的取值范围

?start = a

?end = b

?if function(a) == 0:?

??return a

?elif function(b) == 0:

??return b

?elif function(a) * function(b) 0:?

??print("couldn't find root in [a,b]")

??return

?else:

??mid = (start + end) / 2

??while abs(start - mid) 0.0000001:?

???if function(mid) == 0:

????return mid

???elif function(mid) * function(start) 0:

????end = mid

???else:

????start = mid

???mid = (start + end) / 2

??return mid

def f(x):#定义构造方程式函数

?return math.pow(x, 5) -15*math.pow(x, 4) +85*math.pow(x, 3)-225*pow(x,2)+274*x - 121

print(round(erfenfa(f, 1.5, 2.4),6))

python怎么求解一元二次方程的根?

import numpy as np

def solve_quad(a,b,c):

if a == 0:

print('您输入的不是二次方程!')

else:

delta = b*b-4*a*c

x = -b/(2*a)

if delta == 0:

print('方程有惟一解,X=%f'%(x))

return x

elif delta 0:

x1 = x-np.sqrt(delta)/(2*a)

x2 = x+np.sqrt(delta)/(2*a)

print('方程有两个实根:X1=%f,X2=%f'%(x1,x2))

return x1,x2

else:

x1 = (-b+complex(0,1)*np.sqrt((-1)*delta))/(2*a)

x2 = (-b-complex(0,1)*np.sqrt((-1)*delta))/(2*a)

print(x1,x2)

return x1,x2

Python

是完全面向对象的语言。函数、模块、数字、字符串都是对象。并且完全支持继承、重载、派生、多继承,有益于增强源代码的复用性。Python支持重载运算符和动态类型。相对于Lisp这种传统的函数式编程语言,Python对函数式设计只提供了有限的支持。有两个标准库(functools, itertools)提供了Haskell和Standard ML中久经考验的函数式程序设计工具。

如何用python计算三元方程

(1) variable = a if exper else b

(2)variable = (exper and [b] or [c])[0]

(2) variable = exper and b or c

上面三种用法都可以达到目的,类似C语言中 variable = exper ? b : c;即:如果exper表达式的值为true则variable = b,否则,variable = c

例如:

a,b=1,2

max = (a if a b else b)

max = (a b and [a] or [b])[0] #list

max = (a b and a or b)

现在大部分高级语言都支持“?”这个三元运算符(ternary operator),它对应的表达式如下:condition ? value if true : value if false。很奇怪的是,这么常用的运算符python居然不支持!诚然,我们可以通过if-else语句表达,但是本来一行代码可以完成的非要多行,明显不够简洁。没关系,在python里其实还是有对应的表达方式的。

(责任编辑:IT教学网)

更多

推荐思科认证文章