-1

I want to compute a function which creates the polynomial, if we know the degree and coefficients of that polynomial.

So, that is, I want to ask the user for the degree and for a vector with the coefficients. With this information I want to return the polynomial.

This is what I have right now

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

    a = as.vector(coefficients)

}

Can someone help me further with this? R should treat the polynomial as a vector a = (a0, ..., am)

daedsidog
  • 1,732
  • 2
  • 17
  • 36
Max
  • 109
  • 5
  • So you want to get all the coefficients from a user which are in descending order from higest order to constant? and you want to save these numbers in a vector? – user2974951 Dec 11 '18 at 10:38
  • I want to get a vector a=(a0, ...., am) where a0 is the constant and am is the highest order coefficient. So indeed I want to ask the user of the function the coefficients and save these numbers in a vector, and furthermore I want to create the polynomial which belongs to this vector a – Max Dec 11 '18 at 10:44
  • If the user inputs the coefficients in a given order you can simply save the numbers as you have done so in coefficients. What do you mean by "creating the polynomial..."? Do you want a string with all the variables and their degree? – user2974951 Dec 11 '18 at 10:50
  • No, I just want that R shows me the polynomial of the form 3x^2 - 1 if m=2 and a = (-1, 0, 3) – Max Dec 11 '18 at 11:02
  • Have you seen the `polynom` package? – G5W Dec 11 '18 at 14:15

1 Answers1

2

If you just want to be shown what the polynomial is, you can use:

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"

If you wanted to use this polynomial as a function elsewhere in R, you'd be better off using the polynom package.

mickey
  • 2,168
  • 2
  • 11
  • 20