Difference between fzero and fsolve for one variable

后端 未结 2 1135
借酒劲吻你
借酒劲吻你 2020-12-14 23:47

Is there a difference between using fzero and fsolve for a single variable equation?

2条回答
  •  心在旅途
    2020-12-15 00:27

    Yes, there is. I'll just mention the most straightforward difference between the two:

    fsolve can be used to solve for the zero of a single variable equation. However, fzero will find the zero if and only if the function crosses the x-axis.

    Here's a simple example: Consider the function f=x^2. The function is non-negative for all real values of x. This has a root at x=0. We'll define an anonymous function as f=@(x)x.^2; and try to find the root using both the methods.

    Using fsolve

    options=optimset('MaxIter',1e3,'TolFun',1e-10);
    fsolve(f,0.1,options)
    
    
    Equation solved.
    
    fsolve completed because the vector of function values is near zero
    as measured by the selected value of the function tolerance, and
    the problem appears regular as measured by the gradient.
    
    
    
    
    ans =
    
       1.9532e-04
    

    Not zero, but close.

    Using fzero

    fzero(f,0.1)
    Exiting fzero: aborting search for an interval containing a sign change
        because NaN or Inf function value encountered during search.
    (Function value at -1.37296e+154 is Inf.)
    Check function or try again with a different starting value.
    
    ans =
    
       NaN
    

    It cannot find a zero.

    Consider another example with the function f=@(x)x.^3; that crosses the x-axis and has a root at x=0.

    fsolve(f,0.1)
    
    ans =
    
        0.0444
    
    fzero(f,0.1)
    
    ans =
    
      -1.2612e-16
    

    fsolve doesn't return exactly 0 in this case either. Even using the options I defined above only gets me to 0.0017 with fsolve. However, fzero's answer is correct to within machine precision!. The difference in answers is not because of inefficient algorithms. It's because their objectives are different.

    fzero has a clear goal: find the zero! Simple. No ambiguities there. If it crosses the x-axis, there is a zero and it will find it (real only). If it doesn't cross, it whines.

    However, fsolve's scope is broader. It is designed to solve a system of nonlinear equations. Often you can't find an exact solution to those equations and will have to set a tolerance level, within which you're willing to accept the solution as the answer. As a result, there are a host of options and tolerances that need to be set manually to massage out the exact root. Sure, you have finer control but for finding a zero of a single var equation, I consider it a pain. I'd probably use fzero in that case (assuming it crosses the x-axis).

    Apart from this major difference, there are differences in implementations and the algorithms used. For that, I'll refer you to the online documentation on the functions (see the links above).

提交回复
热议问题