[英]How can I speed up my approximate natural log function?
我已經實現了一個基於截斷泰勒級數的Padé 近似的近似自然對數函數。 精度是可以接受的(±0.000025),但盡管經過了幾輪優化,它的執行時間仍然是標准庫ln
函數的 2.5 倍左右! 如果它不更快,也不那么准確,那它就毫無價值! 盡管如此,我還是用它來學習如何優化我的 Rust 代碼。 (我的時間來自使用criterion
箱。我使用了黑盒,對循環中的值求和,並從結果中創建了一個字符串來擊敗優化器。)
在 Rust Playground 上,我的代碼是:
我的算法概述,它適用於無符號整數的比率:
2ⁿ·N where 1 ≤ N ≤ 2
2ᵈ·D where 1 ≤ D ≤ 2
log(numerator/denominator) = log(2ⁿ·N / 2ᵈ·D) = (nd)·log(2) + log(N) - log(D)
y = x/(2+x)
的替換f(y) = Log((1+y)/(1-y))
= Log((1 + x/(2+x)) / (1 - x/(2+x)))
= Log( (2+2x) / 2)
= Log(1 + x)
x - x²/2 + x³/3 - y⁴/4 + ...
y + y³/3 + y⁵/5 + ...
y + y³/3 + y⁵/5 ...
使用 Padé Approximation y + y³/3 + y⁵/5 ...
2y·(15 - 4y²)/(15 - 9y²)
這是代碼的Padé Approximation部分:
/// Approximate the natural logarithm of one plus a number in the range (0..1).
///
/// Use a Padé Approximation for the truncated Taylor series for Log((1+y)/(1-y)).
///
/// - x - must be a value between zero and one, inclusive.
#[inline]
fn log_1_plus_x(x : f64) -> f64 {
// This is private and its caller already checks for negatives, so no need to check again here.
// Also, though ln(1 + 0) == 0 is an easy case, it is not so much more likely to be the argument
// than other values, so no need for a special test.
let y = x / (2.0 + x);
let y_squared = y * y;
// Original Formula is this: 2y·(15 - 4y²)/(15 - 9y²)
// 2.0 * y * (15.0 - 4.0 * y_squared) / (15.0 - 9.0 * y_squared)
// Reduce multiplications: (8/9)y·(3.75 - y²)/((5/3) - y²)
0.8888888888888889 * y * (3.75 - y_squared) / (1.6666666666666667 - y_squared)
}
顯然,沒有更多的加速了!
迄今為止影響最大的更改是優化我的計算,以獲得最重要的位的位置。 我需要它來減少范圍。
這是我的msb
函數:
/// Provide `msb` method for numeric types to obtain the zero-based
/// position of the most significant bit set.
///
/// Algorithms used based on this article:
/// https://prismoskills.appspot.com/lessons/Bitwise_Operators/Find_position_of_MSB.jsp
pub trait MostSignificantBit {
/// Get the zero-based position of the most significant bit of an integer type.
/// If the number is zero, return zero.
///
/// ## Examples:
///
/// ```
/// use clusterphobia::clustering::msb::MostSignificantBit;
///
/// assert!(0_u64.msb() == 0);
/// assert!(1_u64.msb() == 0);
/// assert!(2_u64.msb() == 1);
/// assert!(3_u64.msb() == 1);
/// assert!(4_u64.msb() == 2);
/// assert!(255_u64.msb() == 7);
/// assert!(1023_u64.msb() == 9);
/// ```
fn msb(self) -> usize;
}
#[inline]
/// Return whether floor(log2(x))!=floor(log2(y))
/// with zero for false and 1 for true, because this came from C!
fn ld_neq(x : u64, y : u64) -> u64 {
let neq = (x^y) > (x&y);
if neq { 1 } else { 0 }
}
impl MostSignificantBit for u64 {
#[inline]
fn msb(self) -> usize {
/*
// SLOWER CODE THAT I REPLACED:
// Bisection guarantees performance of O(Log B) where B is number of bits in integer.
let mut high = 63_usize;
let mut low = 0_usize;
while (high - low) > 1
{
let mid = (high+low)/2;
let mask_high = (1 << high) - (1 << mid);
if (mask_high & self) != 0 { low = mid; }
else { high = mid; }
}
low
*/
// This algorithm found on pg 16 of "Matters Computational" at https://www.jjj.de/fxt/fxtbook.pdf
// It avoids most if-branches and has no looping.
// Using this instead of Bisection and looping shaved off 1/3 of the time.
const MU0 : u64 = 0x5555555555555555; // MU0 == ((-1UL)/3UL) == ...01010101_2
const MU1 : u64 = 0x3333333333333333; // MU1 == ((-1UL)/5UL) == ...00110011_2
const MU2 : u64 = 0x0f0f0f0f0f0f0f0f; // MU2 == ((-1UL)/17UL) == ...00001111_2
const MU3 : u64 = 0x00ff00ff00ff00ff; // MU3 == ((-1UL)/257UL) == (8 ones)
const MU4 : u64 = 0x0000ffff0000ffff; // MU4 == ((-1UL)/65537UL) == (16 ones)
const MU5 : u64 = 0x00000000ffffffff; // MU5 == ((-1UL)/4294967297UL) == (32 ones)
let r : u64 = ld_neq(self, self & MU0)
+ (ld_neq(self, self & MU1) << 1)
+ (ld_neq(self, self & MU2) << 2)
+ (ld_neq(self, self & MU3) << 3)
+ (ld_neq(self, self & MU4) << 4)
+ (ld_neq(self, self & MU5) << 5);
r as usize
}
}
現在我知道 Rust 有一個快速的方法來找到大於或等於一個數字的 2 的最低冪。 我需要這個,但我也需要位位置,因為這相當於我的數字的對數基數 2。 (例如:next_power_of_two(255) 產生 256,但我想要 8,因為它設置了第 8 位。)查看next_power_of_two
的源代碼,我在名為fn one_less_than_next_power_of_two
的私有幫助方法中看到這一行:
let z = unsafe { intrinsics::ctlz_nonzero(p) };
那么是否有一個內在函數可以用來以相同的方式獲取位位置? 它是否在我有權訪問的公共方法中使用? 或者有沒有辦法編寫不安全的代碼來調用一些我不知道的內在代碼(其中大部分是)?
如果我可以調用這樣的方法或內在方法,我懷疑這會大大加快我的程序速度,但也許還有其他事情也會有所幫助。
更新:
磕頭! 我可以使用63 - x.leading_zeros()
來找到最高位的位置! 我只是沒想到從另一端過來。 我會試試這個,看看它是否加快了速度......
一次優化將時間縮短了一半!
我重寫了我的 msb(最重要的位)函數以使用內部使用內部函數的庫函數u64::leading_zeroes
:
fn msb(self) -> usize {
// THIRD ATTEMPT
let z = self.leading_zeros();
if z == 64 { 0 }
else { 63 - z as usize }
}
現在我的對數近似只需要比內在 ln 函數長 6%。 我不太可能做得更好。
經驗教訓:使用內置日志!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.