如何在python代码中包含方程模型

时间:2018-12-28 21:35:47

标签: python

所以我想知道如何在python中包括方程式模型,以便我输入值并根据方程式获得输出。例如,如果我的模型是x ^ 2 + y ^ 2 =输出。如何将这个模型整合到我的代码中,以便在给定x和y的值时得到输出。

3 个答案:

答案 0 :(得分:1)

一个函数可以接收一个或多个输入,并返回一个值:https://www.w3schools.com/python/python_functions.asp

def my_equation(x, y):
    return x**2 + y**2

答案 1 :(得分:0)

有两种方法可以做到这一点,

  1. @ paritosh-singh说,将其编写为函数
  2. 使用允许您执行符号计算的库,例如sympy

使用sympy,您可以这样做

from sympy import *
x, y, z= symbols('x y z')
z = (x^2)+(y^2)

您现在可以为x和y赋值,并以z形式输出。

符号documentation

答案 2 :(得分:0)

您应该使用sympy进行更简洁的计算

from sympy import *
x = Symbol('x')  # define first symbol
y = Symbol('y')  # define second symbol

output = x**2 + y**2 # form the equation

print(output) # print the equation on console

输出

x**2 + y**2

现在像在任何数学方程式中一样替换x和y的值

output.subs({x:1,y:1}) #substitue x::1 and y::1 to get the result

输出

2 # 1**2 ==1 and 1**2==1 and 1+1 =2

为完整起见,您也可以在函数内部定义方程式,但是对于复杂方程式的描述较少。

def func(x,y): return x**2 + y**2

现在您可以使用该函数获取输出

func(1,1) #2