在Python中求解困难的(多项式?)方程

3 投票
2 回答
1412 浏览
提问于 2025-04-17 12:52

我刚开始学习编程(Python是我的第一门语言),但我很喜欢设计算法。目前我正在研究一个整数方程组,但找不到解决我这个特定问题的参考资料。

让我来解释一下。

我有一个方程(可以把它当作一个测试):

raw_input == [(90*x + a) * y] + z

其中a是一个常数。

我的问题是,变量z的变化方式很像斐波那契数列,而变量x是z的步长。简单来说,在z序列的第一个项时,x=0;在第二个项时,x=1。我需要求解y。

确定z的具体过程如下:

where c and d are constants:
#at x = 0
temp = (c+(90*x)) * (d+(90*x))
temp/90 = z(0) 

#at x = 1
new_temp = (c+(90*x)) * (d + (90*x))

new_temp/90 = z(1)  

#for all the rest of the values of z (and x), use:

j = z(@ x=1) - z(@ x=0)
k = j + 180
l = z(@ x=1) + k
print "z(@ x=1) - z(@ x=0) = j"
print "j + 180 = k"
print "k + z(1) = l"
repeat until z > raw_input

this creates the spread of z values by the relation:
j = z(@ x=n) - z(@ x=n-1)
k = j + 180
l = k + z(@ x = n)

我需要跳过(扫描)所有小于x的z值,以测试y是否能得到一个整数解。

这看起来可行吗?

2 个回答

1

我只是把你的伪代码翻译成了Python代码。希望这能对你有所帮助。如果你还没看过的话,建议你去看看这个Python教程

# python 2.7

# raw_input returns string - convert to int
upper_bound = int(raw_input('Upper bound: '))

def z(x):
    'A function to calculate z from x.'
    # c and d are constants
    c = 5
    d = 2
    # integer division here
    return (c + 90*x)*(d + 90*x)/90

# the value of z_0
z0 = z_x = z(0)
# a list to hold the z values z_0, z_1, ...
# the list includes z_0 (when x = 0)
zs = [z0]

x = 1
while z_x < upper_bound:
    z_x = z(x)
    zs.append(z_x)

    j = zs[x] - zs[x - 1]
    k = j + 180
    l = zs[x] + k
    print j, k, l

    x += 1
2

看起来你最好的方法是把给定的方程重新表达成递归关系,然后可以定义一个递归函数来计算你想要的值,或者找到这个关系的封闭形式解。关于递归关系的更多信息可以参考:

最后,根据我的经验,这类问题最好使用数学数值分析软件来解决,比如MatLab、Octave或Mathematica。至少,使用这些软件你可以快速进行部署和测试。

撰写回答