Hi there, I'm trying to right a program for class that 1st assigns random single precission floats from 0 to 1 to the elements 1-d array and then sums them up. Next I'm supposed to compare to this thing called the Kahan summation algorithm for different values of N (array size) using the fractional difference.(adsbygoogle = window.adsbygoogle || []).push({});

I'm just trying to get each of the sums to print out their values now to make sure they doing what they should be doing, not worrying about the fractional difference part yet but keep getting seg faults and I have no idea why.

What's weird is that I think I'm getting them in two different instances. One seg fault seems to come randomly...like I compile and execute the code for the same value of N a few times and every now and then it seg faults, but sometimes not.

The other seg fault seems to occur if N>18.

Last thing...something weird is happening with my sums also because sometimes for som given value like N=15 it gives me the correct summation values, and then every now and again it gives me something ridiculous like sum = 4113476354484640333955072.00000.

Here's my code:

The print statements I just have in there to see what's going on for now.Code (Text):

#include <stdio.h>

#include <stdlib.h>

#include <sys/types.h>

#include <time.h>

#include <assert.h>

float brute(long N,float A[N])

{

long i;

float sum = 0;

for(i=0; i<N; i++)

sum+=A[i];

return sum;

}

float kahan(long N,float A[N])

{

float sum = A[0];

float c = 0;

float y,t;

long i;

for(i=1; i<N; i++)

{

y = A[i] - c ;

t = sum + y;

c = (t - sum) - y;

sum = t;

}

return sum;

}

int main(int argc,char *argv[])

{

long i, N, iSeed;

float A[N], bsum, ksum;

if (argc != 2)

{

fprintf(stderr,"Usage: %s N, where N is the size of the array.\n",argv[0]);

return 1;

}

N = atoi(argv[1]);

assert(N>1);

iSeed = (int) time(NULL) % getpid() + getppid();

printf("Seed = %i\n",iSeed);

srand48(iSeed);

for(i=0;i<N;i++)

{

A[i]=drand48();

printf("elems of A are %f\n",A[i]);

}

bsum = brute(N,A);

ksum = kahan(N,A);

printf("bsum is %f, ksum is %f\n",bsum,ksum);

return 0;

Any insight at all would be greatly appreciated and would help me keep my sanity

**Physics Forums - The Fusion of Science and Community**

Join Physics Forums Today!

The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

# Problem with summation algorithm

Loading...

Similar Threads - Problem summation algorithm | Date |
---|---|

Fortran for Computational Fluid Dynamics Problems | Jan 11, 2018 |

Hacking: Legal and Ethical Problems | Dec 6, 2017 |

Silver Prospector Problem (General Case) | Nov 11, 2017 |

Python Shuffling in classification problems | Nov 11, 2017 |

Parallel Kahan summation | Oct 14, 2013 |

**Physics Forums - The Fusion of Science and Community**