I've been frolicking in pointerless languages too much recently it seems, as I can't get this simple C function (it's within an Obj-C project, thus the use of Core Foundation classes) to work as I want it to...
This function is supposed to take an existing average value and a new value to average in, along with a weight for the existing value (the new value is assumed to just have a weight of 1.) It doesn't return a new value, but instead it should modify the existing average value that's passed in to instead hold a new average value.
I wrote a unit test for this, which is demonstrating that something isn't working for me:
The NSLog statement inside the method is printing out 3.5, which tells me that the arithmetic is right (or it at least happens to pass this test case... I'll write a few more to make sure it's not a fluke,) but it's failing this test and saying that 5 is not equal to 3.5 +/- 0.1, which tells me the existing average isn't actually being updated to the value that the NSLog statement prints out.
It seems obvious to me that I've made a mistake with pointers here somewhere, but I'm not quite sure where... I'm wondering if maybe I should be working with double pointers instead?
This function is supposed to take an existing average value and a new value to average in, along with a weight for the existing value (the new value is assumed to just have a weight of 1.) It doesn't return a new value, but instead it should modify the existing average value that's passed in to instead hold a new average value.
Code:
void averageIn(NSNumber *newNumber, NSNumber *existingAverage,
NSNumber *existingCount)
{
double existingCountDouble = [existingCount doubleValue];
double divisor = existingCountDouble + 1.0;
double existingAverageWeight = existingCountDouble / divisor;
double weightedExistingAverage = [existingAverage doubleValue]
* existingAverageWeight;
double weightedNewNumber = [newNumber doubleValue] / divisor;
existingAverage = @(weightedExistingAverage + weightedNewNumber);
NSLog(@"%@", existingAverage);
}
I wrote a unit test for this, which is demonstrating that something isn't working for me:
Code:
- (void)testAverageIn
{
NSNumber *existingCount = @1;
NSNumber *existingAverage = @5.0;
averageIn(@2.0, existingAverage, existingCount);
XCTAssertEqualWithAccuracy(existingAverage.doubleValue, 3.5, 0.1, @"Messed up averaging...");
}
The NSLog statement inside the method is printing out 3.5, which tells me that the arithmetic is right (or it at least happens to pass this test case... I'll write a few more to make sure it's not a fluke,) but it's failing this test and saying that 5 is not equal to 3.5 +/- 0.1, which tells me the existing average isn't actually being updated to the value that the NSLog statement prints out.
It seems obvious to me that I've made a mistake with pointers here somewhere, but I'm not quite sure where... I'm wondering if maybe I should be working with double pointers instead?
Last edited: