math : add error and gamma functions; sort all functions

pull/1095/head
Koustav Chowdhury 2019-07-12 11:16:40 +05:30 committed by Alexander Medvednikov
parent 9a957ccc18
commit 08866f1331
2 changed files with 51 additions and 18 deletions

View File

@ -90,6 +90,11 @@ pub fn cosh(a f64) f64 {
return C.cosh(a)
}
// degrees convert from degrees to radians.
pub fn degrees(radians f64) f64 {
return radians * (180.0 / Pi)
}
// exp calculates exponement of the number (math.pow(math.E, a)).
pub fn exp(a f64) f64 {
return C.exp(a)
@ -110,11 +115,33 @@ pub fn digits(n, base int) []int {
return res
}
// erf computes the error funtion value
pub fn erf(a f64) f64 {
return C.erf(a)
}
// erfc computes the complimentary error function value
pub fn erfc(a f64) f64 {
return C.erfc(a)
}
// exp2 returns the base-2 exponential function of a (math.pow(2, a)).
pub fn exp2(a f64) f64 {
return C.exp2(a)
}
// factorial calculates the factorial of the provided value.
pub fn factorial(a int) i64 {
if a < 0 {
panic('factorial: Cannot find factorial of negative number')
}
mut prod := 1
for i:= 0; i < a; i++ {
prod *= (i+1)
}
return prod
}
// floor returns the nearest integer equal or lower of the provided value.
pub fn floor(a f64) f64 {
return C.floor(a)
@ -125,6 +152,11 @@ pub fn fmod(a, b f64) f64 {
return C.fmod(a, b)
}
// gamma computes the gamma function value
pub fn gamma(a f64) f64 {
return C.tgamma(a)
}
// gcd calculates greatest common (positive) divisor (or zero if a and b are both zero).
pub fn gcd(a, b i64) i64 {
if a < 0 {
@ -170,6 +202,11 @@ pub fn log10(a f64) f64 {
return C.log10(a)
}
// log_gamma computes the log-gamma function value
pub fn log_gamma(a f64) f64 {
return C.lgamma(a)
}
// log_n calculates base-N logarithm of the provided value.
pub fn log_n(a, b f64) f64 {
return C.log(a) / C.log(b)
@ -201,11 +238,6 @@ pub fn radians(degrees f64) f64 {
return degrees * (Pi / 180.0)
}
// degrees convert from degrees to radians.
pub fn degrees(radians f64) f64 {
return radians * (180.0 / Pi)
}
// round returns the integer nearest to the provided value.
pub fn round(f f64) f64 {
return C.round(f)
@ -240,16 +272,3 @@ pub fn tanh(a f64) f64 {
pub fn trunc(a f64) f64 {
return C.trunc(a)
}
// factorial calculates the factorial of the provided value.
pub fn factorial(a int) i64 {
if a < 0 {
panic('factorial: Cannot find factorial of negative number')
}
mut prod := 1
for i:= 0; i < a; i++ {
prod *= (i+1)
}
return prod
}

View File

@ -31,3 +31,17 @@ fn test_factorial() {
assert math.factorial(5) == 120
assert math.factorial(0) == 1
}
fn test_erf() {
assert math.erf(0) == 0
assert math.erf(1.5) + math.erf(-1.5) == 0
assert math.erfc(0) == 1
assert math.erf(2.5) + math.erfc(2.5) == 1
assert math.erfc(3.6) + math.erfc(-3.6) == 2
}
fn test_gamma() {
assert math.gamma(1) == 1
assert math.gamma(5) == 24
assert math.log_gamma(4.5) == math.log(math.gamma(4.5))
}