JuliaNLSolvers / NLsolve.jl

Julia solvers for systems of nonlinear equations and mixed complementarity problems
Other
324 stars 66 forks source link

solve the nonlinear equation with only one variable #250

Closed gmtang1212 closed 3 years ago

gmtang1212 commented 4 years ago

Dear NLsolve. experts,

Is it possible to solve a nonlinear equation with only one variable? When I try to implement the following function:

using NLsolve function fun!(F, x) F = (x+3)*(x^3-7)+18 end

and solve the nonlinear equation as: nlsolve(fun!, 0.1), it gives me the error message: "ERROR: MethodError: no method matching nlsolve(::typeof(fun!), ::Float64) Closest candidates are: nlsolve(::Any, ::Any, ::AbstractArray; inplace, kwargs...) ..."

Thanks!

fredrikekre commented 4 years ago

NLsolve only solve vector problem AFAIK, but you can define a problem of size 1:

julia> using NLsolve

julia> function fun!(F, x)
           F[1] = (x[1] + 3) * (x[1]^3 - 7) + 18
       end
fun! (generic function with 1 method)

julia> nlsolve(fun!, [0.1])
Results of Nonlinear Solver Algorithm
 * Algorithm: Trust-region with dogleg and autoscaling
 * Starting Point: [0.1]
 * Zero: [-0.464978121172224]
 * Inf-norm of residuals: 0.000000
 * Iterations: 6
 * Convergence: true
   * |x - x'| < 0.0e+00: false
   * |f(x)| < 1.0e-08: true
 * Function Calls (f): 7
 * Jacobian Calls (df/dx): 7
gmtang1212 commented 4 years ago

NLsolve only solve vector problem AFAIK, but you can define a problem of size 1:

julia> using NLsolve

julia> function fun!(F, x)
           F[1] = (x[1] + 3) * (x[1]^3 - 7) + 18
       end
fun! (generic function with 1 method)

julia> nlsolve(fun!, [0.1])
Results of Nonlinear Solver Algorithm
 * Algorithm: Trust-region with dogleg and autoscaling
 * Starting Point: [0.1]
 * Zero: [-0.464978121172224]
 * Inf-norm of residuals: 0.000000
 * Iterations: 6
 * Convergence: true
   * |x - x'| < 0.0e+00: false
   * |f(x)| < 1.0e-08: true
 * Function Calls (f): 7
 * Jacobian Calls (df/dx): 7

Thanks for help! It works!

pkofod commented 3 years ago

That, or try NonlinearSolve.jl or Roots.jl :) It's probably worth adding such methods here at some point, but it will actually be part of NLSolvers.jl in that case. I'll open an issue there.