Adam S
Adam S

Reputation: 41

Conversion from float to double in c++

I wrote a code to calculate error function or double erf(double x). It uses lots of constants in calculations which uses double as well. However, the requirement is to write a code float format or float erf(float). I have to maintain 6 decimals accuracy (typically for float).

When I converted erf(x) into float erf( double x), the results are still the same and accurate. However when I convert x to float or float erf(float x) I am getting some significant errors in small values of x.

Is there a way to convert float to double for x so that precision is still maintained within the code of erf(x)? My intuition tells me that my erf code is good only for double value numbers.

Upvotes: 2

Views: 30890

Answers (2)

Michael Karcher
Michael Karcher

Reputation: 4021

Inside float erf(float x) you can cast the value of x to double at points where precision exceeding float is required.

float demoA(float x)
{
    return x*x*x-1;
}

float demoB(float x)
{
    return static_cast<double>(x)*x*x - 1;
}

In this case, demoB will return a much better value than demoA if the paramerter is close to one. The conversion of the first operator of the multiplication to double is enough, because it causes promotion of the other operand.

Upvotes: 1

dynamic
dynamic

Reputation: 48091

You can't convert from float to double and except that float will have the same precision of double.

With double you get double the precision of a float

Note that in C++ you have erf: http://en.cppreference.com/w/cpp/numeric/math/erf

Upvotes: 1

Related Questions