Problem with summation algorithm

AI Thread Summary
The discussion revolves around a programming issue related to implementing a summation algorithm in C. The user is attempting to create a program that generates random single-precision floats, sums them using both a brute force method and the Kahan summation algorithm, and compares the results. They encounter segmentation faults, particularly when the array size (N) exceeds 18, and inconsistencies in the summation results, with some outputs being unexpectedly large.Key points include the realization that the variable N was uninitialized when used to declare the array A, leading to undefined behavior. This issue was resolved by initializing N before declaring the array. Additionally, the importance of using the `const` qualifier for function parameters that do not modify the input data was discussed, which can enhance code safety and clarity. Compiler warnings were also mentioned as a helpful tool for identifying potential issues in the code. Overall, the user successfully corrected their code and gained a better understanding of proper variable initialization and const correctness in C programming.
Dathascome
Messages
55
Reaction score
0
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.
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:
Code:
#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;

The print statements I just have in there to see what's going on for now.
Any insight at all would be greatly appreciated and would help me keep my sanity
 
Technology news on Phys.org
Code:
int main(int argc, char *argv[])
{
   long i, N, iSeed;
At this point in the program, N is uninitialized: it could be anything from -2147483648 to -2147483647 (on a 32-bit machine).

Code:
   float A[N], bsum, ksum;
This initializes the array A to have length N. And since N is still uninitialized...



Incidentally, if you enable warnings for your C compiler, it would probably have told you this. The option is -Wall if you're using gcc.


Oh, one more thing: const correctness is a good habit, and there's no time like the present to start learning! :smile: Both of your functions do not modify the data; so, for example, you should make the declaration

Code:
float kahan(long N, const float A[N])

Some benefits are:
(1) It let's the compiler catch some of your mistakes
(2) It prevents headaches when you try to interface with other const-correct code
(3) It can result in a faster program
(4) It's "self-documenting": if someone is reading your program, it instantly tells them that this function will not modify A.
 
Last edited:
Thanks much Hurkyl. I changed it so that I initialized N when I first declared it and it seems to work just fine now. Despite that I'm not sure why still. Is the problem just that I tried to use it in A[N] before I specified what N was? I guess that makes sense then.
Also I tried gcc -Wall with my old code and it didn't give me any warning about that, all it said was:
Code:
ps2_1.c: In function 'main':
ps2_1.c:45: warning: implicit declaration of function 'getpid'
ps2_1.c:45: warning: implicit declaration of function 'getppid'

As for your last comment about const float, I've never heard that before. So if I'm using a function that's not going to be altering the value of an argument in my function I use const before hand right? And if the function was going to alter the argument I would just leave it as float with nothing before it?

Well, it works now, and i think I understand what I did wrong :smile:
Thanks again.
 
Last edited:
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.

Similar threads

Back
Top