문제

I tried to code regula falsi method in python using Sympy library, however with certain functions I get an issue telling I'm working with imaginary numbers.

This is my code:

def reglaFalsa(fx,p0,p1,tolerancia,iteracionesMaximas):

    fx = S(fx)
    i = 2
    q0 = fx.subs(x,p0)
    q1 = fx.subs(x,p1)


    while i<=iteracionesMaximas:
        p = p1 - q1*(p1-p0)/(q1-q0)
        if absolute(p-p1) < tolerancia:
            return p

        q = fx.subs(x,p)

        if (q**q1) < 0:
            p0 = p
            q0 = q
        else:
            p1 = p
            q1 = q
        i+= 1
    return p

I called this with following arguments:

fx =3*x+sin(x)-2.71828182846**x, po=0.0, p1=2.0, tolerancia=.0001, iteracionesMaximas=15

and

fx =2*x**2+x-1, po=0.0, p1=1.0, tolerancia=.0001, iteracionesMaximas=15

For sin(x) as argument I get NaN at some variables when SHOULDN'T

I'm getting following Traceback:

Traceback (most recent call last):
  File "../Prácticas/python/ReglaFalsa.py", line 16, in <module>
    print json.dumps(reglaFalsa(y,a,b,tolerancia,iteracionesMaximas), indent=1)
  File "/home/diegoaguilar/Copy/buap/Métodos/Prácticas/python/reglafalsa.py", line 45, in reglaFalsa
    if (q**q1) < 0:
  File "/usr/local/lib/python2.7/dist-packages/sympy/core/decorators.py", line 77, in __sympifyit_wrapper
    return func(a, b)
  File "/usr/local/lib/python2.7/dist-packages/sympy/core/expr.py", line 248, in __lt__
    raise TypeError("Invalid comparison of complex %s" % dif)
TypeError: Invalid comparison of complex 0.0114119631147945 - 0.179219618952309*
도움이 되었습니까?

해결책

Just change the exponentiation (leading to complex results)

q**q1 < 0:

to multiplication

q*q1 < 0: 

Or find another way to compare the signs. C, for instance, has the signbit function.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top