Function to find variance returns 0 - c

I'm working on a program for school that involves finding certain statistics of an array, and one of the things I have to find is the variance, I have a function made for it but for some reason it keeps returning 0
double variance(double * array, unsigned int size, double value)
{
double variance = 0; //Variable used to store the variance
for (unsigned int i = 0; i < size; ++i)
{
if (value > array[i]) //If statement checks to see if you need to subtract the value from the array or the other way around
{
variance += pow((value - array[i]), 2);
}
else
{
variance += pow((array[i] - value), 2);
}
}
variance /= size;
return variance;
}
I've tried going through it with the debugger but I came out with nothing
how I called it:
double varaince = variance(array, size, mean);
printf("\nVariance: %.3lf", variance);
sample output

As #ammoQ commented
double varaince = variance(array, size, mean);
// function name used here.
// printf("\nVariance: %.3lf", variance);
// Use variable name
printf("\nVariance: %.3lf", varaince);

variance/=size;
Should be
variance/=(double)size;
size on its own is stored as a binary integer.

Related

Why is the number declared in the double function not used? (C)

#include <stdio.h>
double calculate_average (int number)
{
static int numberInput = 0; //counter
static int sum = 0;
sum = sum + numberInput;
numberInput++;
return sum / numberInput;
// calculate and return average so far.
}
int main(void)
{
double average;
while (1)
{
int number;
scanf("%d", &number);
if (number == 0)
break; //stops if number == 0
else
average = calculate_average(number);
}
printf("%.1f\n", average);
return 0;
}
As I can personally tell, the function is trying to calculate the average. But why does the main function not use the number in the calculate_average function?
As written, your calculate_average function does not use its given number argument because, nowhere in that function, do you instruct it to do so. Most likely, your sum = sum + numberInput; should really be sum = sum + number; (thus adding that given number to the running total).
A couple of other points:
You should initialize your average variable (to 0.0), otherwise you'll get a crazy result if you give your program an empty list (i.e. give zero as the first entry).
As your function returns a double, it is best to have the sum variable also as a double; otherwise, you are performing integer arithmtic in your calculation, and all returned values will be truncated to integers (losing any fractional parts).
Others will likely point out that you should always check the value returned by your scanf call (it will be 1 if the read operation succeeds) and add code to handle any error; however, addressing that point here is, IMHO, beyond the 'remit' of this question, but see this answer to How validate user input when the expected value is of type int and the entered value is not of type int?.
Here's a possible working version:
#include <stdio.h>
double calculate_average(int number)
{
static int numberInput = 0; //counter
static double sum = 0.0;
sum = sum + number;
numberInput++;
return sum / numberInput;
// calculate and return average so far.
}
int main(void)
{
double average = 0.0; // Always best to initialize variables!
while (1) {
int getal;
scanf("%d", &getal);
if (getal == 0)
break; //stops if getal == 0
else
average = calculate_average(getal);
}
printf("%.1f\n", average);
return 0;
}
Please feel free to ask for any further explanation and/or clarification.

Average of a row in a two-dimensional array in C?

I am having trouble making a program that uses a function call to find the average of the rows in a two dimensional array? I can't get it to work in a larger program. I made this program to try and figure out what I am doing wrong, but to no avail. Any outside help would be greatly appreciated! Here is the testing code:
#include <stdio.h>
double dAvg(double pt[][5],int rows);
int main(void){
int i;
//Initiallize array
double array[3][5]={{3.0,5.0,2.0,1.0,0.0},{4.0,8.0,6.0,3.0,3.0},{7.0,6.0,2.0,3.0,5.0}};
//Computes the average value per row of array
for(i=0;i < 3;i++){
printf("The average of row %d is %f",i,dAvg(array,3));
}
return 0;
}
double dAvg(double pt[][5],int rows){
int r,c;
double sum,avg;
//Calculate sum first
for (c=0,sum=0;c<5;c++){
sum += pt[r][c];
//Find average by dividing the sum by the number of numbers in a row
avg=sum/5;
return avg;
}
}
When I run the program, it just says that the program has stopped working, on top of that, I don't feel confident that I will actually work once that first issue is solved. I am quite new to multi-dimensional arrays and especially so for passing them to functions. Thanks again for any help!
Most errors were present in your dAvg function:
Namely:
You should not pass the entire 2D array if you only need one row there
You should pass the length of the array instead of hardcoding it everywhere (good practice, not a bug)
Your r was kept uninitialised therefore your indexing was not working
You were returning the average in every iteration therefore instead of summing the values you added the first and then you returned before adding the others.
double dAvg(double array[], size_t length){
size_t c;
double sum = 0;
// Calculate sum first
for (c = 0; c < length; c++){
sum += array[c];
}
// Find average by dividing the sum by the number of numbers in a row
return sum / (double) length;
}
int main(void){
int i;
//Initiallize array
double array[3][5] = {{3.0,5.0,2.0,1.0,0.0}, {4.0,8.0,6.0,3.0,3.0}, {7.0,6.0,2.0,3.0,5.0}};
//Computes the average value per row of array
for(i = 0; i < 3; i++){
printf("The average of row %d is %f\n", i, dAvg(array[i], 5));
}
return 0;
}

How can I simplify this working Binary Search code in C?

Hey guys started programming in C few weeks ago learning about algothiritms, just wondering how would you make my code more simple its just a binary search function. But the only thing is you must keep the arguments the same, thanks in advance.
bool search(int value, int values[], int n)
{
int min = values[0];
int max = values[n-1];
int average = (min + max) / 2;
if(average == value)
{
return true;
}
while (average > value)
{
max = average - 1;
average = (min + max) / 2;
}
while (average < value)
{
min = average + 1;
average = (min + max) / 2;
}
if (max < min)
{
return false;
}
if (average == value) {
printf("%i\n", average);
return true;
}
else
{
return false;
}
}
There are a bunch of little things you have to get right in a binary search: handle the length=0 case, make sure the position you test is always valid, make sure you don't overflow (i.e., `(low+high)/2' is not the best way to write that), make sure the new test position is always different from the previous one, etc.
After having done it like a million times, every binary search I write is now done just like this:
bool search(int[] array, int length, int valueToFind)
{
int pos=0;
int limit=length;
while(pos<limit)
{
int testpos = pos+((limit-pos)>>1);
if (array[testpos]<valueToFind)
pos=testpos+1;
else
limit=testpos;
}
return (pos < length && array[pos]==valueToFind);
}
Notice that we only need to do one comparison per iteration, which is faster than most implementations that can do 2. Instead of doing the equality test inside the loop, we reliably find the position where the element to find belongs, using only one comparison per iteration, and then at the end test to see if the element we want is there.
The way we calculate testpos ensures that pos <= testpos < limit, AND it works even if length is the largest possible integer value.
This form also makes it very easy to read off the invariants you want to see, without having to think about strange boundary conditions like high<low. When you come out of the loop, pos==limit so you don't have to worry about using the wrong one, etc.
The condition in this loop is also easily adaptable to different-purpose binary searches like "find where to insert x, ensuring that it goes after all the xs that are already in the array", "find the first x in the array", "find the last x in the array", etc.
This is not a right implementation of binary search ,all conditions must be in one loop ,such as:
Also max must be n-1 and not values[n-1] and min=0 instead of values[0] as also you should compare values[average] with value not just average variable.
bool search(int value, int values[], int n){
int min = 0;
int max = n-1;
int average ;
while(max>=min){
average = (min + max) / 2;
if(values[average] == value)
{
return true;
}
if (values[average] > value)
{
max = average - 1;
average = (min + max) / 2;
}
if (values[average] < value)
{
min = average + 1;
average = (min + max) / 2;
}
}
return false;
}

Function to calculate max value of int not returning desired result

I'm just starting out learning C. I'm trying to find the max value of an int by calculation (actually I'm trying to find the max value of a float through the same method, but I want to test it on int first).
The logic seems to be OK, but my function always returns 0 at the end.
int max_int_helper(int base)
{
int prev_i, next_i, counter;
counter = 1;
prev_i = next_i = base + counter;
// found max
if (next_i < base) {
printf("WE RETURN BASE %d\n", base);
return base;
} else {
while(prev_i <= next_i)
{
prev_i = next_i;
counter *= 2;
next_i = base + counter;
}
max_int_helper(prev_i);
}
}
I call it in my main function like this
printf("max int calculated: %d", max_int_helper(0));
But when I run the thing I get this:
WE RETURN BASE 2147483647
max int calculated: 0
I explicitly put the printf statement, so that I'm "sure" I only return once and the value is correct.
Please point me out where it's going wrong.
It is a recursion. You need to return the value of it.
So in the last line it should be:
return max_int_helper(prev_i);

Code help to determine if point is in Mandelbrot set (check my solution)

Here is my function that tests two points x and y if they're in the mandelbrot set or not after MAX_ITERATION 255. It should return 0 if not, 1 if it is.
int isMandelbrot (int x, int y) {
int i;
int j;
double Re[255];
double Im[255];
double a;
double b;
double dist;
double finaldist;
int check;
i=0;
Re[0]=0;
Im[0]=0;
j=-1;
a=0;
b=0;
while (i < MAX_ITERATION) {
a = Re[j];
b = Im[j];
Re[i]=((a*a)-(b*b))+x;
Im[i]=(2 * a * b) + y;
i++;
j++;
}
finaldist = sqrt(pow(Re[MAX_ITERATION],2)+pow(Im[MAX_ITERATION],2));
if (dist > 2) { //not in mandelbrot
check = 0;
} else if (dist <= 2) { //in mandelbrot set
check = 1;
}
return check;
}
Given that it's correct (can someone verify... or write a more efficient one?).
Here is my code to print it, however it does not work! (it keeps giving all points are in the set). What have I done wrong here?
int main(void) {
double col;
double row;
int checkSet;
row = -4;
col = -1;
while (row < 1.0 ) {
while (col < 1.0) {
checkSet = isMandelbrot(row, col);
if (checkSet == 1) {
printf("-");
} else if (checkSet == 0) {
printf("*");
}
col=col+0.5;
}
col=-1;
row=row+0.5;
printf("\n");
}
return 0;
}
There are some bugs in your code. For example, you do this:
a = Re[j];
b = Im[j];
But at the first iteration, j = -1, so you're getting the value at index -1 of the arrays. That is not what you wanted to do.
Also, why are Re and Im arrays - do you really need to keep track of all the intermediate results in the calculation?
Wikipedia contains pseudocode for the algorithm, you might want to check your own code against that.
Another bug: your function takes int arguments, so the values of your double inputs will be truncated (i.e. the fractional part will be discarded).
You should probably be checking for escape inside the while loop. That is to say, if ((a*a + b*b) > 4) at any time then that pixel has escaped, end of story. By continuing to iterate those pixels, as well as wasting CPU cycles you the values are growing without bound and seem to be exceeding what can be represented in a double - the result is NaN, so your finaldist computation is producing garbage.
I think you would benefit from more resolution in your main. Your code as you've put it here isn't computing enough pixels to really see much of the set.

Resources