Mercurial > sos > sos
view src/math.c @ 6:8676cf44c307
Added functions pow, dup, and drop
pow pulls two numbers from the stack and raises the second pulled to the first
pulled. This was implemented using a exp function I wrote previously and a log
function I just wrote. If an integer power is requestion, it uses the standard
O(log(n)) algorithm... This function can be called using '**'
drop drops the top value of the stack and dup duplicates it...
I also modified the make file so that it supports header file dependencies
author | Jonathan Pevarnek <pevarnj@gmail.com> |
---|---|
date | Sun, 06 Mar 2011 01:38:01 -0500 |
parents | |
children | 25b2b501a5fa |
line wrap: on
line source
double math_iPow(double base, int exp) { double ans = 1; short isNeg = 0; if(exp < 0) { isNeg = 1; exp *= -1; } while(exp > 0) { if(exp%2) { exp -= 1; ans *= base; } else { exp /= 2; base *= base; } } return isNeg ? 1/ans : ans; } double math_exp(double exp) { unsigned int i; //a counter for the loop double ans = 1; double prev = -1; double term = 1; short isNeg = 0; if(exp < 0) { isNeg = 1; exp *= -1; } for(i = 1; ans - prev; i++) { prev = ans; term *= exp/i; ans += term; } return isNeg ? 1/ans : ans; } double math_log(double num) { unsigned int denom = 1; double euler = 2.71828182845904; double ans = 0; double prev = -1; double term = -1; while(num <= -1 || num >= 1) { num /= euler; ans += 1; } for(; ans - prev; denom++) { prev = ans; term *= (-1*(num - 1)); ans += term/denom; } return ans; } double math_pow(double base, double exp) { if(exp == (int) exp) return math_iPow(base, (int) exp); return math_exp(exp*math_log(base)); } double math_abs(double num) { if(num < 0) return num*-1; return num; }