How can I correctly code the calculation of the Langevin function? [$y=\text{coth}(x)-\frac{1}{x}$]

119 Views Asked by At

I am trying to code the Langevin function in C++. The Langevin function is simply:

$y=\text{coth}(x)-\frac{1}{x}$

where $\text{coth}(x) = \frac{e^{2x}+1}{e^{2x}-1}$

I tried coding this in C++ as:

inline double coth(double valueIn) {
    double temp = exp(2 * valueIn);
    return (temp + 1) / (temp - 1);
}

inline double langevinFunction(double valueIn) {
    if (valueIn == 0) {
        return 0;
    }
    else {
        return coth(valueIn) - 1 / valueIn;
    }
}

This function should put out something close to $y=\text{tanh}(x/3)$.

But it's glitching out. For example, if I put in langevinFunction(0.0000001) I get out $-0.00503929$. But the correct value for $\text{coth}(0.0000001)-\frac{1}{0.0000001}$ is $3.5390257835×10^{−8}$ as per Desmos.

Did I screw this up in some way and what did I do wrong if so?

Thanks

References:

https://en.wikipedia.org/wiki/Hyperbolic_functions#Coth

https://en.wikipedia.org/wiki/Brillouin_and_Langevin_functions