如何求解 python 中包含两个变量的方程

How to solve an equation with two variables in python

所以,我想用两个变量求解方程 z(例如,x 和 y 各有 50 个值)。我想计算如下:

import numpy as np
x = np.linspace(0, 50, 51)
y = np.linspace(100, 150, 51)

z=y-x

print z

with open("output_data.csv","w") as out_file:
    for i in range(len(x)):
        #print i
        out_string=""
        out_string+=str(x[i])
        #out_string+=str(real(ky2)[i])
        #print out_string
        out_string += "," + str(z[i])
        out_string += "\n"
        out_file.write(out_string) 

但是我想用所有的y计算第一个x,第二个x用所有的; y 再次出现,依此类推,直到我得到一组 50 个 z 值,每组有 50 个值。然后保存在一个 50 列的文件中。

我的代码正在做的事情是为第一个 x 和第一个 y、第二个 x 和第二个 y 等仅计算 50 个 z。

有什么想法吗?

您需要更改代码以便在 for 循环内计算 z

for i in range(len(x)):
    words = []
    z = y-x[i]
    words.append(str(x[i]))
    words.append(", ".join((str(_z) for _z in z)))
    outfile.write(": ".join(words))
    outfile.write("\n")

使用您的代码,您只计算 z 一次(在循环外),这会造成 yx 的逐项差异,如您所见。

话虽如此,您应该更改代码以不执行 str += ...。如果要累积字符串,请改用列表:

words = []
words.append(str(x[i]) ...