Out of pure curiosity I'm interested if there is a function/package that allows to solve simple nonlinear equations in R?
Let's say I want to (symbolically) solve 0 = C + 1/x^2
. The expected result for the above example is x = sqrt(-1/-C)
I tried the Ryacas
package:
library("Ryacas")
Solve(yacas("C+1/x^2"))
That returns an error:
Error in Sym("Solve(", x, ",", y, ")") : argument "y" is missing, with no default
So I did:
Solve(yacas("C+1/x^2"), 0)
which returns nothing useful:
Yacas vector:
character(0)
I followed the instructions on ?yacas
to install yacas
. It seems as if yacas
works, demo(Ryacas)
generates output. Here is the first portion:
demo(Ryacas)
---- ~~~~~~
Type <Return> to start :
> x <- -3 + (0:600)/300
> exp0 <- expression(x ^ 3)
> exp1 <- expression(x^2 + 2 * x^2)
> exp2 <- expression(2 * exp0)
> exp3 <- expression(6 * pi * x)
> exp4 <- expression((exp1 * (1 - sin(exp3))) / exp2)
> res1 <- yacas(exp4); print(res1)
expression(3 * (x^2 * (1 - sin(6 * (x * pi))))/(2 * x^3))
> exp5 <- expression(Simplify(exp4))
> res2 <- yacas(exp5); print(res2)
expression(3 * (1 - sin(6 * (x * pi)))/(2 * x))
> plot(x, eval(res2[[1]]), type="l", col="red")
Any hints?
We can use package Ryacas
(thanks for the hint @Bhas) an interface to the library yacas
for symbolic equation solving:
library(Ryacas)
expr <- yacas("C+1/x^2 == 0") #Generate yacas expression | note the double equals!
solv <- Solve(expr,"x") # Solve the expression for x
[1] x == root(abs(1/C), 2) * complex_cartesian(cos(argument(-1/C)/2), sin(argument(-1/C)/2))
[2] x == root(abs(1/C), 2) * complex_cartesian(cos((argument(-1/C) + 2 * pi)/2), sin((argument(-1/C) + 2 * pi)/2))
Yacas obviously generates a complex solution because for positive values of C
this equation only has complex roots (square-root of a negative-number). Two solutions is also expected, since we have a quadratic equation.
The complex_cartesian
part refers to the rotation in the complex plane, that is dependend on the value of C (basically the value of a in a complex number of type z=a*i + b
).