2

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.

3
  • 1
    This isn't clear. What counts as "significant errors"? Have you tried just doing erf((float)x) for some double x? Commented Jul 25, 2015 at 5:34
  • Also, are you aware that these functions already exist in the standard library? en.cppreference.com/w/cpp/numeric/math/erf Commented Jul 25, 2015 at 5:34
  • "Is there a way to convert float to double for x so that precision is still maintained " - That is the whole point of double - double the precision Commented Jul 25, 2015 at 6:01

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.