X
    Categories: Allgemein

Solving a polynomial function with R

I found this equation in some textbook.
Then i asked myself if there is an easy way to solve this with R.
Of course, there is.

 

z = seq(-10, 10, by = 1)
i<-10

  y <- z[i]
  
  p = function( x, y ) {
    x^3 + y*x^2 - 2*y^2 - 10*y
  }

  x = seq(-5, 5, by = 0.001) 
  plot(x, p(x,y), type = 'l', col = 'red', ylim = c(-150, 150))
  # adding x-axis and y-axis
  abline(h = 0, v = 0, col = 'blue')

 

 

  # using polyroot() to find the solution(s)
  result <- polyroot( c( (- 2*y^2 - 10*y), 0, y, 1 ) ) 
  i.result <- round( Im( result ), 2 )
  which( i.result == 0 )
  r.result <- Re(result)[which( i.result == 0 )]
   points(x = r.result, y = rep(0, length( r.result )), 
         pch = 16, cex = 2, col = 'green')

z = seq(-100, 100, by = 0.1)
#z <- -3 : 3
#z = seq(-10, 10, by = 0.001)
#z = seq(-3, 50, by = 0.1)
r_solution <- NULL

for( i in 1:length(z) ){
  
  y <- z[i]

  p = function( x, y ) {
    x^3 + y*x^2 - 2*y^2 - 10*y
  }

  result <- polyroot( c( (- 2*y^2 - 10*y), 0, y, 1 ) ) 
  i.result <- round( Im( result ), 2 )
  which( i.result == 0 )
  r.result <- Re(result)[which( i.result == 0 )]
  
  r_solution <- data.frame( rbind( r_solution, cbind( rep( y, length(r.result) ), r.result ) ) ) 
 
}

r_solution

plot( r_solution[,2], r_solution[,1], type = "p", pch = 1, cex = 0.1, col = 'black' )
abline(h = 0, v = 0, col = 'blue')

 

Martin Stoppacher: