Experimental mathematical library in pure Nix, using no external library.
- Because I can.
- Because I want to approximate the network latency between my servers using their latitudes/longitudes. No, I don't want to run
traceroute
between my servers every now and then.
{
inputs = {
nix-math.url = "github:xddxdd/nix-math";
};
outputs = inputs: let
math = inputs.nix-math.lib.math;
in{
value = math.sin (math.deg2rad 45);
};
}
abs [x]
,fabs [x]
: Absolute value ofx
arange [min] [max] [step]
: Create a list of numbers frommin
(inclusive) tomax
(exclusive), addingstep
each time.arange2 [min] [max] [step]
: Same asarange
, but includesmax
as well.div [a] [b]
: Dividea
byb
with no remainder.mod [a] [b]
: Modulos of dividinga
byb
.pow [a] [b]
: Returnsa
to the power ofb
. Only supports integer forb
!factorial [x]
: Returns factorial ofx
.x
is an integer,x >= 0
.sin [x], cos [x], tan [x]
: Trigonometric function. Takes radian as input.atan [x]
: Arctangent function.deg2rad [x]
: Degrees to radian.sqrt [x]
: Square root ofx
.x >= 0
.haversine [lat1] [lon1] [lat2] [lon2]
: Returns distance of two points on Earth for the given latitude/longitude.
sin
function is implemented with its Taylor series: forx >= 0
,sin(x) = x - x^3/3! + x^5/5!
. Calculation is repeated until the next value in series is less than epsilon (1e-10
).cos
issin (pi/2 - x)
.tan
issin x / cos x
.- For
sin
,cos
andtan
, result error is within 0.0001% as checked by unit test.
- For
atan
is implemented with this estimation algorithm: https://stackoverflow.com/a/42542593. This is faster and more accurate than usingatan
's Taylor series, because its Taylor series does not converge as fast assin
.- For
atan
, result error is within 0.0001%.
- For
sqrt
is implemented with Newtonian method. Calculation is repeated until the next value is less than epsilon (1e-10
).- For
sqrt
, result error is within1e-10
.
- For
haversine
is implemented based on https://stackoverflow.com/a/27943.
Unit test is defined in tests/test.py
. It invokes tests/test.nix
which tests the mathematical functions with a range of inputs, and compares the output to the same function from Numpy.
To run the unit test:
nix run .
MIT.