python中的物理方程

时间:2017-10-25 04:05:22

标签: python equation

我想制作一个可以计算物理方程的程序,用户输入不同的参数:我知道它很简单:

v=5
t=7
s=v*t
print(s)

它唯一的计算s = v*t;但是,当我想要v的等式时,如果显示错误。硬编码v = s/t给出了正确的结果:

s=5
t=7
v=s/t
print(v)

我想要一个可以用不同的用户输入解决的方程式;也就是说,如果用户输入vt,则等式将返回s = v*t,如果用户输入st,则等式将返回{{1} }}

4 个答案:

答案 0 :(得分:4)

您可以使用关键字参数:

def solve_equation(v=None, t=None, s=None):
    if v is not None and t is not None:
        return v * t   # s case
    elif s is not None and t:  # t not None and not 0            
        return s / t   # v case
    else:
        raise ValueError   #"t should be defined or not zero"


print(solve_equation(v=10, t=2))
print(solve_equation(s=2, t=7))

输出:

20
0.2857142857142857

请注意,如果您使用的是python 2,则必须传递浮点数。

答案 1 :(得分:1)

我不确定这是否是您想要的,但您可以定义三个单独的函数,每个函数对应一个变量。例如,

def s(v, t):
    return v*t

def v(s, t):
    return s/t

def t(s, v):
    return s/v

答案 2 :(得分:1)

假设你在谈论零加速度“svt”方程式(或者甚至是恒定加速度“suvat”方程式,如果你有更复杂的要求),那么检测什么是未知的是一个简单的问题,然后填补空白

以下代码提供了一个函数,它将执行此操作以及一些测试代码,以便您可以看到它的实际效果:

# Returns a 3-tuple containing [displacement(s), velocity(v), time(t)],
#    based on the existence of at least two of those.
# If all three are given, the displacement is adjusted so that the
#    equation 's = vt' is correct.

def fillInSvt(s = None, v = None, t = None):
    # Count the unknowns, two or more means no unique solution.

    noneCount = sum(x is None for x in [s, v, t])
    if noneCount > 1: return [None, None, None]

    # Solve for single unknown (or adjust s if none).

    if noneCount == 0 or s is None: return [v*t, v, t]
    if v is None: return [s, s/t, t]
    return [s, v, s/v]

# Test code.

print(fillInSvt(99,4,6))         # Show case that adjusts s.

print(fillInSvt(None,4,6))       # Show cases that fill in unknown.
print(fillInSvt(24,None,6))
print(fillInSvt(24,4,None))

print(fillInSvt(24,None,None))   # Show "not enough info" cases.
print(fillInSvt(None,4,None))
print(fillInSvt(None,None,6))
print(fillInSvt(None,None,None))

输出显示在存在唯一解决方案的所有情况下都会填充元组:

[24, 4, 6]
[24, 4, 6]
[24, 4.0, 6]
[24, 4, 6.0]
[None, None, None]
[None, None, None]
[None, None, None]
[None, None, None]

答案 3 :(得分:0)

def h2(v,d,t):
    title_ar = 'السرعة'
    title_en = 'speed'
    if v=='':
        print("v= ","%.2f"% (d/t),"m/s")
    elif d=='':
        print("d= ","%.2f"% (v*t),"m")
    elif t=='':
        print("t= ","%.2f"% (d/v),"s")
    else:
        print("please write all data.")

h2('', 2,6)
h2(70,'',8)
h2(25,3,'')