Inverse Error Function in C

后端 未结 3 1679
萌比男神i
萌比男神i 2021-01-02 04:12

Is it possible to calculate the inverse error function in C?

I can find erf(x) in which calculates the error function, but I

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-02 04:27

    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); 
    
    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]);
    
    figure(2);
    e = f-y;
    plot(x, e);
    

    MATLAB Plots:

提交回复
热议问题