2 回答

TA貢獻(xiàn)1909條經(jīng)驗 獲得超7個贊
我認(rèn)為算法是不同的。例如方差:
/* 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 );
這看起來不像你的方差。如果您要重現(xiàn)算法以便它們執(zhí)行完全相同的操作,那么 Go 版本應(yīng)該產(chǎn)生相同的結(jié)果。Go 只是在做標(biāo)準(zhǔn)的 IEEE 754 浮點運算。
至于“順序重要嗎?”這個問題。確實如此。由于浮點算術(shù)不精確,您在計算時會丟失信息。大多數(shù)時候它不會產(chǎn)生太大的不同,但有時算法可能非常容易受到這些變化的影響。(因此以代數(shù)方式重新排列您的公式可能不會在實際代碼中得到相同的答案)
您經(jīng)常會在這些庫中發(fā)現(xiàn)算法旨在解決這些問題,因此它們通??雌饋聿幌袷怯字傻膶崿F(xiàn)。例如mean,通常是一個微不足道的函數(shù),但以下是它在 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;
}
因此,除非您完全匹配算法,否則您的答案將略有不同。(這并不一定意味著你的程序是錯誤的)
通常用于此的一種解決方案是在一個非常小的數(shù)字(math.Abs(expected-result) < ?,您定義 ?: 的地方const ? = 0.0000001)內(nèi)進(jìn)行相等比較,而不是使用==.

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