Find a root of a function in a given range

前端 未结 3 1604
感动是毒
感动是毒 2021-01-19 15:35

I have a set of functions f_t with several roots (two actually). I want to find the \"first\" root and doing this with fsolve works fine most of th

3条回答
  •  灰色年华
    2021-01-19 15:56

    Classically, you could use root:

    import numpy as np
    from scipy.optimize import root
    
    def func(x, t):
        return x ** 2 - 1. / t
    
    t = 5000
    
    res = root(func, 0.5, args=(t, )).x[0]
    print res
    

    That would print the positive one, in this case 0.0141421356237.

    If you want to specify the range and determine all roots within this interval, you can use chebpy:

    from chebpy import chebfun
    
    x = chebfun('x', [-100000, 100000])
    t = 5000
    f = x ** 2 - 1. / t
    
    rts = f.roots()
    print rts
    

    This would print both the positive and the negative root, in this case

    [-0.01413648  0.01413648]
    

    If you only want to look in the positive range, you can change

    x = chebfun('x', [-100000, 100000])
    

    to

    x = chebfun('x', [0, 100000])
    

    I am, however, not sure how to use infinity, but you can just use a very high number for practical purposes, I think.

提交回复
热议问题