Dear Sir/Madam,
My purpose is to write an R function to solve the quadratic equation
ax2+bx+c=0.
The input should be an array of a, b, and c from a data set
a b c
1 4 3
1 4 5
0 2 5
0 0 6
The output with the possibility of complex roots and one root or no root
should look like the following.
A B C REAL1 IM1 REAL2 IM2
1 4 3 -1.0 . -3 .
1 4 5 -2.0 1 -2 -1
0 2 5 -2.5 . . .
0 0 6 . . . .
I get the code in reading in the coefficient data and outputing the results
to a data set for eventual printing. Please help me in adding the R code
that solves for the quadratic in place of the comments.
a <- c(1,1,0,0)
b <- c(4,4,0,0)
c <- c(3,5,5,6)
SolveQuad <- function(a,b,c)
{
## Put the answer in y.solution a vector of length 4
y.solution <- rep(-999,4)
if (a == 0)
{
if (b!= 0) {y.solution[1]<- -1*c/b}
} else
## Put your R code here
} else
{
## Put your R code here
}
y.solution
}
# Interate through the coefficients
y <- matrix(0,nrow=4,ncol=4)
for (k in 1:4)
{
y[k,] <-SolveQuad(a[k],b[k],c[k])
}
y
Thanks very much for all the help!!!!!
yuying shi
[[alternative HTML version deleted]]