# Numerical Analysis in C: Solving a sum

1. Apr 17, 2012

### chill_factor

1. The problem statement, all variables and given/known data

Solve the following sum: Ʃ f(0.01k) from k=1 to k=100000 where f(k) = √minimum of (1,k) * exponential(maximum of (1.5, k)*maximum of (1.5,k))

2. Relevant equations

See above.

3. The attempt at a solution

/*I've written a C program to solve this problem. it compiles. However, when I run it, the answer is 0 which is incorrect. What's wrong with either my methodology or coding?*/

#include<stdio.h>
#include<math.h>

main(){

int k; /*declare k variable */
double min; /*declare minimum variable*/
double max; /*declare maximum variable*/
double funcResult; /*declare function result*/
double sum; /*declare sum result*/

/*create minimum function*/

if(0.01*k<1){
min=0.01*k;
}
else{
min=1;
}

/*create maximum function*/

if(0.01*k>1.5){
max=0.01*k;
}
else{
max=1.5;
}

/*create funcResult function*/

funcResult=sqrt(min*exp(-max*max));

/*compute the sum */

sum=0;

for(k=1;k<=100000;k++){

sum=(sum+funcResult);

}

printf("The answer to this sum is: %lf\n and the funcResult is %lf",sum,funcResult);

}

2. Apr 17, 2012

### Staff: Mentor

You are setting sum to sum + funcResult 100,000 times, but funcResult keeps the value that it was given before the loop started.

You need to code funcResult as an actual function, not as a variable. Either that, or do the computation inside your loop.

3. Apr 17, 2012

### chill_factor

Thank you!!! I obtained non-zero answers!

4. Apr 17, 2012

### Staff: Mentor

From your comments, you seem to believe that you are writing functions, but you're not.

For example, there's this code:
Code (Text):

/*create minimum function*/

if(0.01*k<1){
min=0.01*k;
}
else{
min=1;
}
[/quote]
This code gets executed once, with garbage (uninitialized) values for k and min. I can't predict what min will be set to, since you haven't put a known value into k.

The situation is the same for max and funcResult. The values for these three variables are set before the loop begins execution, so any changes to k inside the loop have no effect on min, max, or funcResult.

5. Apr 17, 2012

### Ray Vickson

Unless I misunderstand your f(k), it looks like this problem will involve serious numerical overflow. I think you are saying
$$f(k) = \sqrt{\min(1,5) \exp(\max(1.5,k)^2)},$$ and you want to evaluate f up to f(100000/100) = f(1000). However, f(1000) = 0.1741612873e217148, so the last terms in your sum will be immense. Are you sure you have not mis-stated the problem?

RGV