首页 > 解决方案 > 如何使用 sympy 求解方程?

问题描述

我需要编写代码来求解 McLachlan 模型方程。在用 for 循环中的不同参数(x 和 h)替换后找到 c 的值怎么做??!

我有用matlab编写的代码,可以满足我的需要..但同样的想法不适用于python我收到错误!

Traceback (most recent call last):
  File "func.py", line 18, in <module>
    (x * f ** (1 / h) - x * c ** (1 / h))
NameError: name 'c' is not defined

这是我在 python 中的代码

import numpy
from sympy import Symbol, solve

v_p = input("Enter perculion threshold:")
sigma_P = input("Enter MOFs conductivity:")
sigma_F = input("Enter filler conductivity:")

p = float(sigma_P)
f = float(sigma_F)

x = Symbol('c')
A = (1 - float(v_p) / float(v_p))

for h in numpy.arange(1, 1.5, 0.1):
   for x in numpy.arange(0, 1, 0.1):
       print(solve([
           (
                   (x * f ** (1 / h) - x * c ** (1 / h))
                   /
                   (f ** (1 / h) + A * c ** (1 / h))
           )
           /
           (
                   (p ** (1 / h) - c ** (1 / h) - x * p ** (1 / h) + x * c ** (1 / h))
                   /
                   (p ** (1 / h) + A * c ** (1 / h))
           )
       ], [c]))

这是用matlab编写的代码

syms sigma_c
A=4.777
sigma_f = 550
sigma_p = 1.7 * 10 ^ (-11)

for h = 2:10
    for j = 1:10
        v_f = 0.1 * j;
        ans = solve([(((v_f) * (((sigma_f) ^ (1 / h)) - ((sigma_c) ^ (1 / h))))/(((sigma_f) ^ (1 / h)) + ((A) * ((sigma_c) ^ (1 / h))))) + (((1 - v_f) * (((sigma_p) ^ (1 / h)) - ((sigma_c) ^ (1 / h))))/(((sigma_p) ^ (1 / h)) + ((A) * ((sigma_c) ^ (1 / h))))) == 0], [sigma_c]);
        answer = double(ans)
        arr(h,j) = answer;
        end
end

disp(arr)

标签: pythonsympysolver

解决方案


您收到“SyntaxError:无效语法”,因为并非所有括号都已关闭。下面的代码建议进行格式化,以便在计算中提供更多概述。我希望 ')' 应该在第 25 行添加,但这显然是模棱两可的,你应该用你自己的想法来验证这一点。

请注意,'c' 仍然未定义,没有它您的代码将无法工作。

import numpy
from sympy import Symbol, solve

v_p = input("Enter perculion threshold:")
sigma_P = input("Enter MOFs conductivity:")
sigma_F = input("Enter filler conductivity:")

p = float(sigma_P)
f = float(sigma_F)

x = Symbol('c')
A = (1 - float(v_p) / float(v_p))

for h in numpy.arange(1, 1.5, 0.1):
    for x in numpy.arange(0, 1, 0.1):
        print(solve([
            (
                    (x * f ** (1 / h) - x * c ** (1 / h))
                    /
                    (f ** (1 / h) + A * c ** (1 / h))
            )
            /
            (
                    (p ** (1 / h) - c ** (1 / h) - x * p ** (1 / h) + x * c ** (1 / h))
                    /
                    (p ** (1 / h) + A * c ** (1 / h))
            )
        ], [c]))

推荐阅读