用R中的次数和系数计算多项式

时间:2018-12-11 10:32:49

标签: r function coefficients

如果我们知道该多项式的次数和系数,我想计算一个创建多项式的函数。

因此,我想问用户输入度数和带有系数的向量。有了这些信息,我想返回多项式。

这就是我现在拥有的

polynomial <- func{
    m = readline("What is the degree of the polynomial?")
    coefficients = readline("What are the coefficients of the polynomial?")

    a = as.vector(coefficients)

}

有人可以进一步帮助我吗? R应将多项式视为向量a =(a0,...,am)

1 个答案:

答案 0 :(得分:2)

如果只想显示 多项式,则可以使用:

polynomial = function(){
    # Accept user input
    input_m = as.numeric(readline("Degree? "))
    input_coef = readline("Coefficients (separated by a single space): ")

    m = input_m
    # Split string
    coef = strsplit(input_coef, " ")[[1]]

    # Check for correct number of coefficients
    if (length(coef) != m + 1)
        stop("Incorrect number of coefficients for given m.")

    # Add "+" to non-first positive coefficients
    coef[-1][as.numeric(coef[-1]) > 0] = paste0("+", coef[-1][as.numeric(coef[-1]) > 0])
    zeros = as.numeric(coef) == 0

    # Make the polynomial
    output = paste0(coef[!zeros], "*x^", (m:0)[!zeros], collapse = "")
    # Replace "*x^0" with nothing
    output = sub("\\*x\\^0", "", output)

    return (output)
    }

> polynomial()
Degree? 3
Coefficients (separated by a single space): 5 -3 0 2.1
[1] "5*x^3-3*x^2+2.1"

如果您想将此多项式用作R中其他位置的函数,最好使用polynom包。