Reputation: 883
I'm working on a Function that will do a POW long handed. It's an assignment in dealing with function calls and variable hand offs rather than how to use math.h.
The function works to what the spec wants but I want to add (for my own ACD issues) a range filter.
I must use the prototype as given (double base, int exp).
I can't add any headers...stuck with stdio.h and stdlib.h only.
I wanted to do log base(max_VALUE) > exp to check the exponent and base don't exceed the maximum value that the double may hold. That worked.
What was happening though when I did testing of the power calcs using base 10 and any exponent over 22 was I'd get some erronious results. With 10^50 I would get a 1, 16 0s a 1 and the remainding 0s. If I did 10^23 I'd get 99999999999999992000000.00000.
I'm curious as to what's going on at that magic 16 spot. What would be a good value to toss in there as a static value just to get the thing to work? Ideally I wanted to use size_of() and work out the max value but right now I don't really care too much about that.
The filtering is all about my need to have code that doesn't crash because of poor input validation.
Thanks in advance for your help!
Here's what I have for the Function...
double Power( double base, int exp )
{
int i;
double max_VALUE = 1;
double power_sum = 1;
// calculation of system specific max variable value - I would have used limits.h but thought
// the idea of lab was to have restraints on us so I did it long-handed.
for ( i=0; i<(sizeof(base)*8); i++ )
{
max_VALUE *= 2;
}
// 'Out of Range' filter
while (max_VALUE > base)
{
max_VALUE = max_VALUE / base; // max_VALUE is divided by base until it becomes less
i++; // than base. 'i' is the highest exponent this system can handle
} // for the given base. ( Slight fudge factor because I'm rounding it off. )
if ( abs(exp) > i )
{
printf("\n\n*** Out of RANGE Error ***\n\n");
return 0;
}
// Power Calculation
for(i=0;i < abs(exp) ;i++) // Loop equals exponent value
{
power_sum *= base;
}
power_sum = ( exp < 0) ? ( 1 / power_sum ) : power_sum; //corrects for negative exponent
return power_sum;
}
Upvotes: 0
Views: 116
Reputation: 183968
I'm curious as to what's going on at that magic 16 spot.
double
s have a 53-bit mantissa (usually, if IEEE754), that corresponds to roughly 16 decimal digits. So representing numbers as double
s gives you about 16 correct decimal digits, beyond that it may all be rounding error.
Upvotes: 1