代码之家  ›  专栏  ›  技术社区  ›  You_Tli

Python-错误无法确定关系型的真值(Newton Raphson)

  •  0
  • You_Tli  · 技术社区  · 9 月前

    我使用Newton-Raphson方法进行根查找,遇到了错误:“无法确定Relational的真值。”我真的很感激任何关于可能导致这种情况的见解。谢谢!

    import sympy as sp
    import numpy as np
    from scipy import io, integrate, linalg, signal
    from scipy import io, integrate, linalg, signal
    from scipy.sparse.linalg import cg, eigs
    import sympy as sp
    import math
    from math import *
    from sympy import  *
    from sympy import symbols
    from sympy import lambdify
    
    # Define symbolic variable 
    # Define symbols for c1, c2, c3, and other variables
    x,c1, c2, c3, k = symbols('x c1 c2 c3 k')
    A11=4.9091
    B11=0.0294
    D11=0.0014
    I0=140.8182
    I1=0.1191
    I2=0.0307
    # Define expressions for e1, e2, e3, e4, e5, and e6
    e1 = -I0 * x / A11
    e2 = I1 * x / A11
    e3 = B11 / A11
    e4 = -(B11 * e1 + I1 * x) / (B11 * e3 - D11)
    e5 = -I0 * x / (B11 * e3 - D11)
    e6 = (-B11 * e2 + I2 * x) / (B11 * e3 - D11)
    
    # Define U and W as symbolic lists
    U = [0 for _ in range(50)]  # Extend this as needed
    W = [0 for _ in range(50)]  # Extend this as needed
    
    # Initialize the given boundary conditions
    U[0] = 0
    U[1] = c1
    W[0] = 0
    W[1] = 0
    W[2] = c2
    W[3] = c3
    
    # Loop over N and K, as in the Maple code
    for N in range(12, 30, 2):
        for K in range(0, N):
            U[K+2] = (e1*U[K] + e2*(K+1)*W[K+1] + e3*(K+3)*(K+2)*(K+1)*W[K+3]) / ((K+2)*(K+1))
            W[K+4] = (e4*(K+1)*U[K+1] + e5*W[K] + e6*(K+2)*(K+1)*W[K+2]) / ((K+4)*(K+3)*(K+2)*(K+1))
    
        # Define the sum equations
        f1 = sum(U[k] for k in range(N+1))  # Sum for U
        f2 = sum(W[k] for k in range(N+1))  # Sum for W
        f3 = sum(k * W[k] for k in range(N+1))  # Sum for W weighted by k
        f11=sp.expand(f1)
        f22=sp.expand(f2)
        f33=sp.expand(f3)
    
        # Collect terms involving c1, c2, c3
        eqt1 = sp.collect(f11, {c1, c2, c3})
        eqt2 = sp.collect(f22, {c1, c2, c3})
        eqt3 = sp.collect(f33, {c1, c2, c3})
    
        system = [eqt1, eqt2, eqt3]
    
        # Extract the coefficients of c1, c2, c3
        A = sp.Matrix([[eqt.coeff(c1) for eqt in system],
                       [eqt.coeff(c2) for eqt in system],
                       [eqt.coeff(c3) for eqt in system]])
    
        # Create the vector for the constants
        b = sp.Matrix([eqt.subs({c1: 0, c2: 0, c3: 0}) for eqt in system])
    
        # Compute the determinant of the matrix A
        det = A.det()
        ddet=diff(det,x)
        
        # Defining Function
        def f(x):
            return  det
    
        # Defining derivative of function
        def g(x):
            return ddet
        
        # Implementing Newton Raphson Method
        
        def newtonRaphson(x0,e,Nst):
            print('\n\n*** NEWTON RAPHSON METHOD IMPLEMENTATION ***')
            step = 1
            flag = 1
            condition = True
            while condition:
                if g(x0) == 0.0:
                    print('Divide by zero error!')
                    break
                
                x1 = x0 - f(x0)/g(x0)
                #print('Iteration-%d, x1 = %0.6f and f(x1) = %0.6f' % (step, x1, f(x1)))
                x0 = x1
                step = step + 1
                
                if step > Nst:
                    flag = 0
                    break
                
                condition = abs(f(x1)) > e
            
            if flag==1:
                print('\nRequired root is: %0.8f' % x1)
            else:
                print('\nNot Convergent.')
    
    
        # Input Section
        x0 =0.1 #input('Enter Guess: ')
        e = 0.0001#input('Tolerable Error: ')
        Nst =10# input('Maximum Step: ')
    
        # Converting x0 and e to float
        x0 = float(x0)
        e = float(e)
    
        # Converting N to integer
        Nst = int(Nst)
    
    
        #Note: You can combine above three section like this
        # x0 = float(input('Enter Guess: '))
        # e = float(input('Tolerable Error: '))
        # N = int(input('Maximum Step: '))
    
        # Starting Newton Raphson Method
        newtonRaphson(x0,e,Nst)
        
    
    
        
    
    

    我使用Newton-Raphson方法进行根查找,遇到了错误:“无法确定Relational的真值。”

    2 回复  |  直到 9 月前
        1
  •  0
  •   chrslg    9 月前

    对于什么是sympy符号存在着深刻的误解。

    sympy.symbols('x') 与python变量无关 x 除此之外,大多数时候,我们 x=sympy.symbols('x') ,所以python变量 x 是一个表示符号的sympy对象 x .

    这就是你所做的。

    之后

    x,c1, c2, c3, k = symbols('x c1 c2 c3 k')
    

    变量 x 包含符号 x

    但内部代码 f

        def f(x):
            return  det
    

    变量 x 是函数的自变量 f . 虽然符号 x (用于象征性表达 det )与那无关。

    让我们用一个更简单的例子。

    你所做的相当于

    x=sympy.symbols('x')
    det=2*x+1
    
    def f(x):
       return det
    
    print(f(12))
    

    显然,预计它将返回25。但它不会。 det 是象征性表达 2x+1 所以 f 返回符号表达式 2x+1 无论你向它传递了什么论点,在这里都永远不会使用。您选择为参数命名的事实 f x 在这里无关紧要。

    你可能想做的是

    x=sympy.symbols('x')
    det=2*x+1
    
    f = sympy.lambdify(x, det)
    
    print(f(12))
    

    lambdify 将构建一个函数,其参数是传递的符号(如果传递多个符号,则返回一个或多个符号),当该符号被计算为作为所述构建函数的参数传递的值时,返回值是表达式(det)的计算值。

    所以,简而言之,这里 f(12) 确实会返回25。

    再次注意,在这里,重要的是符号,而不是包含它的变量的名称。

    让我们重新表述一下这个例子

    varX=sympy.symbols('symx')
    det=2*varX+1
    # det is 2symx+1
    
    f = sympy.lambdify(varX, det)
    # f is a function f(argx) that returns the value of expression det if 
    # symx is replaced by argx
    print(f(12))
    # 25
    

    所以,就你的情况而言

    f=lambdify(x, det)
    g=lambdify(x, ddet)
    

    没有声称它会起作用(似乎还有其他数字问题)。但它解决了你目前的问题

    (我注意到你进口了 兰姆迪菲 ,但从未使用过。所以我想我在这里说的话对你来说应该不是全新的)

        2
  •  0
  •   J Suay    9 月前

    牛顿法是一种数值方法,但你的f(x)和g(x)仍然是符号性的。你需要对它们进行评估。经过以下更改,代码在我的计算机中运行。但是,由于我没有看到预期的输出,我无法证明它按您的预期运行。

    # Compute the determinant of the matrix A
        det1 = A.det()
        ddet=diff(det1,x)
        
        # Defining Function
        def f(xvalue):
            return  det1.subs({x  : xvalue})
    
        # Defining derivative of function
        def g(xvalue):
            return ddet.subs({x : xvalue})
    
    推荐文章