Maximum Likelihood estimation
You have a typo in your formula
#derivative of fun1.
fun1.tag &lt;- function(theta){
  y &lt;- 0
  for(i in 1:length(x)){
    y &lt;- y + 2*(theta^2+(x[i]^2)-20*x[i]-1)/((1+(x[i]-theta)^2)^2)
  }
  return(y)
}

There is y +  missing inside the loop.