[英]Python GEKKO using function in model with if-statement
[英]Defining function using if-statement
def roots4(a,b,c,d):
d = b * b - 4 * a * c
if a != 0 and d == 0:
roots4(a,b,c,d)
x = -b/ (2*a)
if a != 0 and d > 0:
roots4(a,b,c,d)
x1 = (-b + math.sqrt(d)) / 2.0 / a
x2 = (-b - math.sqrt(d)) / 2.0 / a
if a != 0 and d < 0:
roots4(a,b,c,d)
xre = (-b) / (2*a)
xim = (math.sqrt(d))/ (2*a)
print x1 = xre + ixim
strx1 = "x2 = %6.2f + i %6.2f" %(xre, xim)
print strx1
這是我的項目代碼的一部分。 我想做的是定義roots4(a,b,c,d)
。 例如,在a != 0 and d == 0
的情況下,然后roots4(a,b,c,d)
將通過求解方程x = -b/ (2*a)
來求x
。 等等...我不知道我在做什么錯。 有小費嗎?
你可能堆滿了
...
roots4(a,b,c,d)
...
這會導致無限循環
首先,為什么需要遞歸調用? d
參數有什么用?
其次, ixim
是什么? 應該是xim * 1j
嗎? 您對print x1 = xre + ixim
什么print x1 = xre + ixim
?
如果只想在d < 0
情況下打印,就可以了
from math import sqrt
def roots4(a,b,c):
if a != 0.:
x_left = -b/(2*a)
d = b * b - 4 * a * c
if d == 0.:
x_right = 0.
elif d > 0.:
x_right = sqrt(d) / (2 * a)
else:
xim = sqrt(-d) / (2 * a)
strx1 = "x1 = %6.2f + i %6.2f" %(x_left, xim)
print strx1
strx2 = "x2 = %6.2f - i %6.2f" %(x_left, xim)
print strx2
x_right = xim * 1j
x1 = x_left + x_right
x2 = x_left - x_right
else:
raise ValueError("incorrect leading coefficient in given square equation")
好吧,看來您已經使用遞歸函數進行了無限循環。 現在看來,您將永遠不做任何計算
d = b * b - 4 * a * c
一遍又一遍地。
考慮程序流程。 每次到達
roots4(a,b,c,d)
您將再次回到頂部。
正如評論和jimmy的回答所指出的,不需要遞歸調用。
這是一個如何糾正它(以您喜歡的方式進行適應)的示例:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import math
def roots4(a, b, c):
"""Prints the solutions of ax² + bx + c = 0, if a != 0"""
if a == 0:
print 'This function is meant to solve a 2d degree equation, '\
'not a 1st degree one.'
else:
d = b * b - 4 * a * c
solutions = []
if d == 0:
solutions = [str(-b / (2 * a))]
elif d > 0:
solutions = [str((-b + math.sqrt(d)) / 2.0 / a),
str((-b - math.sqrt(d)) / 2.0 / a)]
elif d < 0:
xre = str((-b) / (2 * a))
xim = str((math.sqrt(-d)) / (2 * a))
solutions = [xre + " + i" + xim,
xre + " - i" + xim]
print "\nEquation is: {}x² + {}x + {} = 0".format(a, b, c)
if len(solutions) == 1:
print "There's only one solution: " + solutions[0]
else:
print "Solutions are: " + " and ".join(solutions)
roots = [(0.0, 0.0, 0.0),
(0.0, 0.0, 1.0),
(0.0, 2.0, 4.0),
(1.0, 2.0, 1.0),
(1.0, -5.0, 6.0),
(1.0, 2.0, 3.0)]
for r in roots:
roots4(*r)
輸出:
$ ./test_script2.py
This function is meant to solve a 2d degree equation, not a 1st degree one.
This function is meant to solve a 2d degree equation, not a 1st degree one.
This function is meant to solve a 2d degree equation, not a 1st degree one.
Equation is: 1.0x² + 2.0x + 1.0 = 0
There's only one solution: -1.0
Equation is: 1.0x² + -5.0x + 6.0 = 0
Solutions are: 3.0 and 2.0
Equation is: 1.0x² + 2.0x + 3.0 = 0
Solutions are: -1.0 + i1.41421356237 and -1.0 - i1.41421356237
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.