math: use libc wrappers for math.log2/1, math.log10/1, math.log1p/1 and math.log_b/1; make assert math.log10(10) == 1.0 pass in the common case (#23129)

This commit is contained in:
Delyan Angelov 2024-12-11 12:06:33 +02:00 committed by GitHub
parent 23bcd915ca
commit fdfb3896e9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 56 additions and 5 deletions

View File

@ -1,17 +1,45 @@
module math module math
fn C.log(x f64) f64 fn C.log(x f64) f64
fn C.log2(x f64) f64
fn C.log10(x f64) f64
fn C.log1p(x f64) f64
fn C.logb(x f64) f64
fn C.logf(x f32) f32 fn C.logf(x f32) f32
// log returns the natural logarithm of x (float64) // log returns the natural logarithm of x (float64)
@[inline] @[inline]
pub fn log(a f64) f64 { pub fn log(x f64) f64 {
return C.log(a) return C.log(x)
}
// log2 returns the binary logarithm of x (float64).
// The special cases are the same as for log.
@[inline]
pub fn log2(x f64) f64 {
return C.log2(x)
}
// log10 returns the decimal logarithm of x (float64).
// The special cases are the same as for log.
@[inline]
pub fn log10(x f64) f64 {
return C.log10(x)
}
// log1p returns log(1+x).
@[inline]
pub fn log1p(x f64) f64 {
return C.log1p(x)
}
// log_b returns the binary exponent of x.
pub fn log_b(x f64) f64 {
return C.logb(x)
} }
// log returns the natural logarithm of x (float32) // log returns the natural logarithm of x (float32)
@[inline] @[inline]
pub fn logf(a f32) f32 { pub fn logf(x f32) f32 {
return C.logf(a) return C.logf(x)
} }

23
vlib/math/log_test.v Normal file
View File

@ -0,0 +1,23 @@
import math
fn test_log_base() {
assert math.log(math.e) == 1.0
}
fn test_log2_base() {
assert math.log2(2.0) == 1.0
}
fn test_log10_base() {
// Note: `assert math.log10(10.0) == 1.0` currently fails, when the pure V implementation is used with
// `./v -exclude @vlib/math/*.c.v vlib/math/log_test.v`
assert math.veryclose(math.log10(10.0), 1.0)
}
fn test_log1p_base() {
assert math.log1p(math.e - 1) == 1.0
}
fn test_log_b_base() {
assert math.log_b(2.0) == 1.0
}