Is it possible to calculate the inverse error function in C?
I can find erf(x)
in <math.h>
which calculates the error function, but I can't find anything to do the inverse.
The inverse error function inverf x occurs in the solution of nonlinear heat and diffusion problems [ 1 ]. It provides exact solutions when the diffu- sion coefficient is concentration dependent, and may be used to solve certain moving interface problems.
. It is implemented in the Wolfram Language as InverseErf[x]. (OEIS A069286) can be written in closed form.
The error function erf is a special function. It is widely used in statistical computations for instance, where it is also known as the standard normal cumulative probability. The complementary error function is defined as erfc ( x ) = 1 − erf ( x ) .
erfinv( X ) computes the inverse error function of X . If X is a vector or a matrix, erfinv(X) computes the inverse error function of each element of X .
Quick & dirty, tolerance under +-6e-3. Work based on "A handy approximation for the error function and its inverse" by Sergei Winitzki.
C/C++ CODE:
float myErfInv2(float x){
float tt1, tt2, lnx, sgn;
sgn = (x < 0) ? -1.0f : 1.0f;
x = (1 - x)*(1 + x); // x = 1 - x*x;
lnx = logf(x);
tt1 = 2/(PI*0.147) + 0.5f * lnx;
tt2 = 1/(0.147) * lnx;
return(sgn*sqrtf(-tt1 + sqrtf(tt1*tt1 - tt2)));
}
MATLAB sanity check:
clear all, close all, clc
x = linspace(-1, 1,10000);
% x = 1 - logspace(-8,-15,1000);
a = 0.15449436008930206298828125;
% a = 0.147;
u = log(1-x.^2);
u1 = 2/(pi*a) + u/2; u2 = u/a;
y = sign(x).*sqrt(-u1+sqrt(u1.^2 - u2));
f = erfinv(x); axis equal
figure(1);
plot(x, [y; f]); legend('Approx. erf(x)', 'erf(x)')
figure(2);
e = f-y;
plot(x, e);
MATLAB Plots:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With