Reputation: 3807
I'm trying to make a simple function to do an exponential curve fit given a dataset. I've written the following:
function expCurveFit(d){
var sum_x2 = 0, sum_lny = 0, sum_x = 0, sum_xlny = 0, n = d.length;
for(var i=0;i<d.length;i++){
var x = d[i][0];
var y = d[i][1];
sum_x2 += x^2, sum_lny += Math.log(y), sum_x += x, sum_xlny += x*Math.log(y);
}
var a = ((sum_lny*sum_x2)-(sum_x*sum_xlny))/((n*sum_x2)-sum_x^2);
var b = ((n*sum_xlny)-(sum_x*sum_lny))/((n*sum_x2)-sum_x^2);
return [a,b];
}
but a and b don't seem to be correct. I'm working from the basic formula at Wolfram. The inputted array is in the form [[x1,y1],[x2,y2]...[xn,yn]]
. Anyone have working suggestions, plug-ins, libraries, or revised functions?
Upvotes: 2
Views: 2208
Reputation: 335
Besides the XOR operator as marked as the answer for this question, there's a mistake on the a and b coefficients.
The curve that you will fit using this method is Y = B * exp(A * x)
, as is written in Wolfram, but B = b
and A = exp(a)
!
So you have to change the return [a,b]
to [ Math.exp(a), b]
(if you want to use this array as a "equation")
Upvotes: 1
Reputation: 141827
^ is the XOR operator in JavaScript, not exponentiation.
Replace x^2
with Math.pow(x,2)
or x*x
and do the same for both places where you have sum_x^2
.
Upvotes: 5