您好,谢谢您的宝贵时间,
我意识到我的问题实际上与以下主题中的问题非常相似:How to get coefficients of polynomial expression
但是,我想详细说明这个问题。
我已经编写了一个程序,当给出一个向量,该向量相对于该多项式内的多项式以递增程度填充了多项式的系数时,将以类似的方式输出一个填充有该多项式的本原系数的向量。例如,当我想知道表达式y = 54s ^ 2-36s + 3的原语时,我会将向量(3,-36,54)输入到程序中,然后将返回向量(0,3, -18,18),因为此y的图元是18s ^ 3-18s ^ 2 + 3s。该程序的代码如下:
# Define function degree
degree <- function() {
# First asks for degree
m1 <- readline("Please input the degree of your polynomial.")
# Checks if degree is integer and non-negative
m2 <- as.integer(m1)
if ((m2 == m1)&(m1>0)) {
print(paste("The degree of your polynomial is", m1))
}
if(m2 != m1) {
print("The degree of a polynomial must be an integer.")
degree()
}
if(m1 < 0) {
print("The degree of a polynomial must be non-negative.")
degree()
}
# Last output of degree is defining numeric m
m <- as.numeric(m1)
}
# Define function polynomial
polynomial <- function() {
# First calls on the degree function
m <- degree()
# Then asks for coefficients
a <- readline("Please input the coefficients of your polynomial in order of their
ascending degree separated by a space, such as: a[0] a[1] a[2] ... a[m]")
# Creates vector a filled with these coefficients
a <- strsplit(a, " ")
a <- a[[1]]
a <- as.numeric(a)
# Checks if any non-numeric values were entered for the coefficients
if (is.na(sum(a)) == TRUE) {
print("The program does not allow for non-numeric coefficients.")
polynomial()
}
# Checks if length of vector is equal to degree + 1
if ((length(a) == m+1)) {
print("Your polynomial can be represented by the vector:")
print(a)
}
if ((length(a) != m+1)) {
print("Please input a coefficient for the degree of each separate monomial within
your polynomial.")
polynomial()
}
# Last output of polynomial is defining numeric a
a <- as.numeric(a)
}
# Define function primitive
primitive <- function() {
# Call on function polynomial
a <- polynomial()
# Calculate the primitive
p <- c()
p[1] <- 0
for (i in 1:length(a)){
p[i + 1] <- a[i]/i
}
print(paste("The degree of your primitive is", (length(p) - 1)))
print("The primitive of your polynomial can be represented by the vector")
print(p)
}
现在,这本身可能并不是完美无瑕的,但是效果很好。但是,现在的问题是我希望能够以多项式形式计算微分方程的Picard迭代。现在,我非常有信心自己可以编写此代码,所以我只想问问与我继续工作有关的内容。
我本质上希望能够将任何表达式简化为多项式形式(如果表达式允许这样做,但我们假设是这样)。例如,如果我的表达式是6(3s-1)^ 2,那么我想让R简化为54s ^ 2-36s + 6并将其放入向量形式(6,-36,54),这样我就可以用我的书面程序原语运行它。我尝试使用软件包rSympy获得以下信息:
sympy("expand(6*(3*s - 1)**2)")
哪个给我输出
[1] "6 - 36*s + 54*s**2"
但是我不知道如何从此输出中获取(数字)向量(6,-36、54)。
在我链接的线程中,我看到他们使用了功能'gregexpr'。但是我不知道此函数的功能以及它的工作方式,我一生都无法弄清楚为获得所需矢量必须确切输入该函数的内容。我不喜欢编写我不理解的代码。请帮忙解释一下!