Square Sums

Hi, I'm learning to program on C++. I want to declare a function to program this division of sums where I've two arrays having xi and yi terms respectively, and a constant "a".

f(x) = ∑ yi (a^2 -(x−xi)^2)^2 / ∑ (a^2 -(x−xi)^2)^2

How can i do this? I tried this at my first time, what naturally didn't work.

1
2
3
4
5
6
7
8
9
double f1(double x)   
{
	double ms = 0;
	int a = 2
	for(int i=0;i<100;i++)
	{	
		double ms += col2[i]*pow(pow(a,2)-pow(x-col1[i],2),2)/(pow(a,2)-pow(x-col1[i],2),2);	
	};
}


Thanks in advance
Last edited on
Remove the double at the beginning of line 7. You only need that when you're declaring a new variable.
And don't forget to return the final value of ms.

Another problem: you forgot a pow immediately after the division. You need to be careful with those kinds of mistakes, because expressions of the form (x, y) are valid, and you'll end up driving yourself mad trying to find why you're getting wrong results.

Also, a performance tip: avoid calls to pow() with natural exponents below 4 or so. Here's what the expression looks like refactored:
1
2
3
4
5
double exp1 = x-col1[i];
exp1 *= exp1;
double exp2 = a * a - exp1;
exp2 *= exp2;
ms += col2[i] * exp2 / exp2;
This also helps make expressions clearer, and makes bugs such as the one you have there, easier to see.
Your code refers to col2 and col1, which it does not know about. Neither do we.

What is in the first sum clause and what is in the second?

Let me quess:
X = (a^2 -(x−xi)^2)^2
Y = ∑ yi X
Z = ∑ X
f(x) = Y / Z

Both Y and Z are separate sums. You have only one. (2+4)/(2+1) != (2/2)+(4/1)
Topic archived. No new replies allowed.