From 631d989d00ace0692a96011e21d4d16481a22735 Mon Sep 17 00:00:00 2001 From: Jeffrey Wilcke Date: Wed, 18 Nov 2015 19:02:32 +0100 Subject: [PATCH] library/math: Added standard math functions Added standard math library, including: * Two dimensional euclidean distance * Square root * Linear interpolation --- library/math.sol | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 library/math.sol diff --git a/library/math.sol b/library/math.sol new file mode 100644 index 0000000..84efea5 --- /dev/null +++ b/library/math.sol @@ -0,0 +1,28 @@ +/// Standard math library. +contract Math { + /// @dev Returns the square root of x. + function sqrt(uint x) returns (uint) { + uint y = x; + while( true ) { + uint z = (y + (x/y))/2; + uint w = (z + (x/z))/2; + if( w == y) { + if( w < y ) return w; + else return y; + } + y = w; + } + } + + /// @dev Returns the, two dimensional, eucledian distance between two points. + function 2dEucDist(uint x_a, uint y_a, uint x_b, uint y_b) returns (uint) { + return sqrt((x_a - y_b) ** 2 + (y_a, - x_b) ** 2); + } + + /// @dev Returns the linear interpolation between a and b + function lerp(uint x_a, uint y_a, uint x_b, uint y_b, uint delta) returns (uint x, uint y) { + x = x_a * delta + x_b * delta; + y = y_a * delta + y_b *delta; + return x, y; + } +}