1

I am using a simple polynomial to fit a curve.

poly <- function(a, b, c, x) a * x^2 + b * x + c

I'd like to find the value of x that results in the maximum value of the curve. Currently I create a grid with a range of x from 20000 to 50000, run the function for each row, then use max() on the result. It works, but I have a lot of groups and it creates a big dataframe every time I do it. It is very clunky and I feel like there must be a better way.

Some typical coefficients are:

a <- -0.000000179
b <- 0.011153167
c <- 9.896420781
Nazer
  • 3,654
  • 8
  • 33
  • 47

3 Answers3

1

If you rearrange your function so the variable you want to maximize is first and you set the default values like so:

poly <- function(x, a, b, c) a * x^2 + b * x + c

formals(poly)$a <- -0.000000179
formals(poly)$b <- 0.011153167
formals(poly)$c <- 9.896420781

Then you can use the optimize function to maximize over your interval:

optimize(poly, c(20000, 50000), maximum = T)

$`maximum`
[1] 31154.1

$objective
[1] 183.6298

Where $maximum is the x value at which the maximum occurs and $objective is the height.

LMc
  • 12,577
  • 3
  • 31
  • 43
0

You could use optim. I think the other solutions answered in this thread are more appealing, but I'll write this up for completeness:


a <- -0.000000179
b <- 0.011153167
c <- 9.896420781

o <- optim(
    par=list(x=0),
    fn=function(x){ -poly(a,b,c,x=x) },
    method="Brent",
    lower=-50e3, upper=50e3
)

Output:


> o
$par
[1] 31154.1

$value
[1] -183.6298

$counts
function gradient 
      NA       NA 

$convergence
[1] 0

$message
NULL

Sirius
  • 5,224
  • 2
  • 14
  • 21
0

If a is negative, maximum of parabola a * x^2 + b * x + c is reached at -b/(2*a) :

a<0
#[1] TRUE

-b/(2*a)
#[1] 31154.1
Waldi
  • 39,242
  • 6
  • 30
  • 78