成本函数方程解析



我正在努力解决这个任务:

对于下面的成本函数,其中C是生产x单位产品的成本,求边际成本函数。x给定时的边际成本是多少?C (x) = 0.05 x ^ 3 + 0.8 x ^ 2 + 40 + 100;x = 500

我如何从这个字符串解析粗体值,公式?可以在类似的字符串中重复。

这是我的解决方案,它将方程分解为需要求和的对象,然后单独计算每个对象:

def clean(string):
# Removes unnecesarry parts of input
return string.rstrip(';').split('=')[1]
def parse(string):
parts = string.split('+')
objs = []
for part in parts:
mult_pow = part.split('x')
if len(mult_pow) == 2:
# Both multiplier and power present
obj = (
float(mult_pow[0]),
float(mult_pow[1].lstrip('^')) if mult_pow[1] else 1.0
)
else:
if '^' in mult_pow[0]:
# Only power present
obj = (
1.0,
float(mult_pow[0].lstrip('^'))
)
else:
# Only multiplier present
obj = (
float(mult_pow[0]),
0
)

objs.append(obj)
return objs
def evaluate(parsed_objects, x):
result = 0
for obj in parsed_objects:
result += obj[0] * x**obj[1]
return result
def solve(equation, x):
cleaned_str = clean(equation)
parsed_objects = parse(cleaned_str)
result = evaluate(parsed_objects, x)
return result
x = 500
input_str = 'C(x)=0.05x^3+0.8x^2+40x+100;'
result = solve(input_str, x)
print(result)

输出:

6470100.0

最新更新