tags:

views:

119

answers:

2

My question is this: is there a way to always use the extended precision versions of mathematical functions - such as sqrt, exp, &c - without using an explicit cast when providing a single or double precision argument?

For example I want this functionality, without the hassle of the casting:

float x=15.0;
float answer;

answer=sqrt((long double)x);

This comes in the context of scientific computing, where many iterations of a loop containing such functions is required. Even though at the end of the process I only require single precision, the floating point errors that result during each iteration can sum to something significant after a few thousand iterations. Thanks.

+2  A: 

Cast to long double before the loop and at the end cast result back to single precision?

jitter
+2  A: 

In C

If you #include <math.h>, which declares such function as returning a double and accepting double arguments, the compiler will do the cast for you implicitily.

#include <math.h>

/* ... */

int x = sqrtl(sqrt(sqrtf(42)));
/* 1                     ^^    implicit cast of int to float          */
/* 2               ^^^^^^^^^   implicit cast of float to double       */
/* 3          ^^^^^^^^^^^^^^^  implicit cast of double to long double */
/* 4    ^^^^^^^^^^^^^^^^^^^^^^ implicit cast of long double to int    */
pmg
True in C, not in C++ where they're overloaded.
MSalters
By including cmath in C++ you also gain access to the expl, sinl, cosl, sqrtl versions of mathematical functions - thanks pmg.
Ian Buss