Reputation: 11
The following problem is given: https://i.sstatic.net/4kan7.jpg
Write a function polyPrint, which prints the polynomial of Equation (1) in a nice way. For example, if a corresponds to the vector c(2, 0, 1, -2, 5), then polyPrint(a) is supposed to print:
2 + x^2 + (-2)*x^3 + 5*x^4
Note how polyPrint is supposed to handle the cases where an element of a is either 0, 1 or negative!
At the moment I am using a loop and cat. Thats pretty rough because I need to do a lot of exeptions with ifelse statements for 1,0 and any negative.
Are there any other functions I could be using to streamline this process?
# Regular function
polyFunction <- function(x,a){
n <- seq(1, length(a))
sum(ax^(n-1))
}
# Printing the calculation method
a <- c(2,0,1,-2,5)
polyPrint <- function(a){
n <- seq(1, length(a))
for(i in n){
result <- c()
result <- c(result, cat(a[i],'x^', 1+i, '+ '))
}
}
polyPrint(a)
The expected output is a polynomial function that has this format:
p(x) = a0 + a1x + a2x^2 + ... + anxn
At the moment I am getting 2 *x^ 2 + 0 *x^ 3 + 1 *x^ 4 + -2 *x^ 5 + 5 *x^ 6 +
with the vector c(2, 0, 1, -2, 5)
Upvotes: 1
Views: 165
Reputation: 16178
I think you have an error in the way you are aggregating values and also the way you are taking in considerations special values (0,1, negative values). Here an example of how you can do that (maybe not the best solution, but it does the job):
polyPrint <- function(a){
formule = NULL
for(i in 1:length(a))
{
if(a[i]==0){}
else{
if(i == 1) {formule = a[i]}
else{
if(a[i]<0){formule = paste0(formule, " + (",a[i],")x^",i)}
else{
if(a[i] == 1){formule = paste0(formule," + x^",i)}
else{formule = paste0(formule, " + ", a[i],"x^",i)}
}
}
}
}
print(formule)
}
And the result for a <- c(2,0,1,-2,5)
:
> polyPrint(a)
[1] "2 + x^3 + (-2)x^4 + 5x^5"
Upvotes: 1