使用 Ryacas 包或替代方案在 R 中符号求解非线性方程 [英] Solve nonlinear equation symbolically in R with `Ryacas` package or an alternative
问题描述
出于纯粹的好奇,我对是否有一个函数/包可以解决 R 中的简单非线性方程感兴趣?
Out of pure curiosity I'm interested if there is a function/package that allows to solve simple nonlinear equations in R?
假设我想(象征性地)解决0 = C + 1/x^2
.上面例子的预期结果是 x = sqrt(-1/-C)
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)
我尝试了 Ryacas
包:
library("Ryacas")
Solve(yacas("C+1/x^2"))
返回一个错误:
Sym("Solve(", x, ",", y, ")") 中的错误:缺少参数y",没有默认
Error in Sym("Solve(", x, ",", y, ")") : argument "y" is missing, with no default
所以我做到了:
Solve(yacas("C+1/x^2"), 0)
它没有返回任何有用的东西:
which returns nothing useful:
Yacas vector:
character(0)
我按照 ?yacas
上的说明安装 yacas
.看起来好像 yacas
有效,demo(Ryacas)
生成输出.这是第一部分:
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?
推荐答案
我们可以使用包Ryacas
(感谢@Bhas 的提示)一个接口到库yacas
对于符号方程求解:
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 显然会生成一个复数解,因为对于 C
的正值,这个方程只有复数根(负数的平方根).由于我们有一个二次方程,因此也需要两个解.complex_cartesian
部分是指复平面内的旋转,即依赖于 C 的值(基本上是 z=a*i + b
).
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
).
这篇关于使用 Ryacas 包或替代方案在 R 中符号求解非线性方程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!