使用`Ryacas`包或替代方案在R中象征性地求解非线性方程

问题描述 投票:1回答:1

出于纯粹的好奇心,如果有一个函数/包允许解决R中的简单非线性方程,我会感兴趣吗?

假设我想(象征性地)解决0 = C + 1/x^2。上述例子的预期结果是x = sqrt(-1/-C)


我试过Ryacas包:

library("Ryacas")
Solve(yacas("C+1/x^2"))

这会返回一个错误:

Sym中的错误(“Solve(”,x,“,”,y,“)”):缺少参数“y”,没有默认值

所以我做了:

Solve(yacas("C+1/x^2"), 0)

返回没有用的东西:

Yacas vector:
character(0)

我按照?yacas上的说明安装yacas。似乎yacas工作,demo(Ryacas)产生输出。这是第一部分:

    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")

任何提示?

r symbolic-math solver equation-solving
1个回答
1
投票

我们可以使用包Ryacas(感谢提示@Bhas)库yacas的接口来进行符号方程求解:

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类型的复数中的a的值)。

© www.soinside.com 2019 - 2024. All rights reserved.