Skip to content
Physics and Astronomy
Home Our Teaching Resources C programming Appendix
Back to top
On this page
Contents

Appendix: A little more about our exponential function

The occasional appendices and optional examples in this module are for advanced material that you will not need for this module. They are intended for enthusiastic students who are interested in going further in programming for its own sake.

Problems with the test

Our function includes the test:

if (value == 0.0 && exponent < 0 ) 

where value is a double. But we have already warned against testing floating-point values for exact equality (and the additional compiler warnings we have enables on Code::Blocks will object to this).

So how do we get round this?

Check if value is "too small"

if (fabs(value) < 1e-99 && exponent < 0 ) 

This sort of works but how do we decide on the minimum limit?

Check the answer at the end, not the value at the beginning

isfinite()

Overall, the best answer is to use a feature we have not met yet (but will cover in the lecture on debugging): isfinite(), defined inside math.h, which checks if its argument is a "proper" number.

If we remove the test on value at the beginning of the function we can test the final result at the end:

  while (exponent < 0) {
    result /= base;
    ++exponent;
  }
  if ( ! isfinite(base))
    printf("WARNING: underflow for negative exponent\n");
  
  return base;
}

Notice here we have not returned zero but just passed the value back up to the calling function (so we should change the comment at the top of the function).

And finally...

  • We may ask: "why bother?". Well, one answer is that we may be programing a small "embedded" system, say in a fridge where the exp() function may not be available.
  • Speed: if exponent is very large this function could be very slow. We could come up with a neat algorithm where we calculated exponent squared, exponent to the fourth, to the eighth, etc and multipled them together. We will show an example of this later in the course.
  • It's tedious! Dealing with errors and edge cases takes a lot of time and effort. The usual rule applies: the larger the number of people using the program the larger the amount of time we will spend looking for errors.
Log in
                                                                                                                                                                                                                                                                       

Validate   Link-check © Copyright & disclaimer Privacy & cookies Share
Back to top