2 回答

TA貢獻1909條經驗 獲得超7個贊
我認為算法是不同的。例如方差:
/* Do the MA calculation using tight loops. */
/* Add-up the initial periods, except for the last value. */
periodTotal1 = 0;
periodTotal2 = 0;
trailingIdx = startIdx-nbInitialElementNeeded;
i=trailingIdx;
if( optInTimePeriod > 1 )
{
while( i < startIdx ) {
tempReal = inReal[i++];
periodTotal1 += tempReal;
tempReal *= tempReal;
periodTotal2 += tempReal;
}
}
/* Proceed with the calculation for the requested range.
* Note that this algorithm allows the inReal and
* outReal to be the same buffer.
*/
outIdx = 0;
do
{
tempReal = inReal[i++];
/* Square and add all the deviation over
* the same periods.
*/
periodTotal1 += tempReal;
tempReal *= tempReal;
periodTotal2 += tempReal;
/* Square and add all the deviation over
* the same period.
*/
meanValue1 = periodTotal1 / optInTimePeriod;
meanValue2 = periodTotal2 / optInTimePeriod;
tempReal = inReal[trailingIdx++];
periodTotal1 -= tempReal;
tempReal *= tempReal;
periodTotal2 -= tempReal;
outReal[outIdx++] = meanValue2-meanValue1*meanValue1;
} while( i <= endIdx );
這看起來不像你的方差。如果您要重現算法以便它們執行完全相同的操作,那么 Go 版本應該產生相同的結果。Go 只是在做標準的 IEEE 754 浮點運算。
至于“順序重要嗎?”這個問題。確實如此。由于浮點算術不精確,您在計算時會丟失信息。大多數時候它不會產生太大的不同,但有時算法可能非常容易受到這些變化的影響。(因此以代數方式重新排列您的公式可能不會在實際代碼中得到相同的答案)
您經常會在這些庫中發現算法旨在解決這些問題,因此它們通??雌饋聿幌袷怯字傻膶崿F。例如mean,通常是一個微不足道的函數,但以下是它在 GSL 中的計算方式:
double
FUNCTION (gsl_stats, mean) (const BASE data[], const size_t stride, const size_t size)
{
/* Compute the arithmetic mean of a dataset using the recurrence relation
mean_(n) = mean(n-1) + (data[n] - mean(n-1))/(n+1) */
long double mean = 0;
size_t i;
for (i = 0; i < size; i++)
{
mean += (data[i * stride] - mean) / (i + 1);
}
return mean;
}
因此,除非您完全匹配算法,否則您的答案將略有不同。(這并不一定意味著你的程序是錯誤的)
通常用于此的一種解決方案是在一個非常小的數字(math.Abs(expected-result) < ?,您定義 ?: 的地方const ? = 0.0000001)內進行相等比較,而不是使用==.

TA貢獻1982條經驗 獲得超2個贊
正如 Caleb 和 Matteo 的評論/答案所建議的那樣,即使代碼排序方式的細微差異也會導致浮點值的差異。
我最終確認,至少在一個小樣本量的情況下,完全像 TA-Lib 一樣實現代碼會產生正確的浮點值。正如預期的那樣,即使稍微偏離 TA-Lib (C) 實現也會導致浮點值的微小差異。
- 2 回答
- 0 關注
- 231 瀏覽
添加回答
舉報