asik / FixedMath.Net

Fixed point math C# library
Other
591 stars 126 forks source link

Add Pow, Ln, and Exp functions #12

Closed sam-vdp closed 6 years ago

sam-vdp commented 6 years ago

Add Exp and Ln functions and Pow based on the combination of both. Ln uses Newton's method to approximate the solution, this code was ported from libfixmath, which your license already covers. The Exp function uses a power series

sam-vdp commented 6 years ago

Thank you very much for pushing back on the crappy previous solution and for your very good idea of using log2. I've added Log2 and Ln based on it, which don't have the previous precision issues.

Furthermore I've removed Exp and added Pow2, which splits the exponentiation into an integer and fractional part and handles large values much better, while maintaining precision for smaller values.

Please note that the Pow test still has some heuristics regarding the expected precision. Firstly, for large results the absolute errors become larger, which needs to be compensated. Secondly, some test cases are slightly pathological. E.g. Pow(1-Fix64.FromRaw(1), Fix64.MaxValue) is evaluated by doing Pow2(Fix64.MaxValue * Fix64.Log2(1-Fix64.FromRaw(1)), which becomes Pow2(Fix64.MaxValue * Fix64.Precision) which of course is not very precise.

asik commented 6 years ago

I've made a few stylistic changes locally and merged. Thank you for this contribution!