Haskell中的foldl和folder的数值问题

Haskell中的foldl和folder的数值问题

本文介绍了Haskell中的foldl和folder的数值问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Haskell脚本,用于计算函数f(x) = (2- x) - (2^3 - x^3/12)

I have the following Haskell script which computes the function f(x) = (2- x) - (2^3 - x^3/12)

calc x = (x - (x ^ 3) / 12)
calc2 x = (calc 2) - (calc x)

calcList1 :: [Float] -> Float
calcList1 l = foldl (+) 0.0 (map calc2 l)

calcList2 :: [Float] -> Float
calcList2 l = foldr (+) 0.0 (map calc2 l)

test1 :: Float -> Float
test1 step = (calcList1 l) - (calcList2 l)
    where
        l = [0.0,step..2.0]

函数calcList1calcList2在每个列表上运行calc2函数,然后分别使用foldlfoldr对列表求和.我期望两个函数都返回相同的答案,但事实并非如此.

Function calcList1 and calcList2 run calc2 function on each of list and then uses foldl and foldr respectively to sum the list. I was expecting both function to return the same answer but it does not.

*Main> test1 0.1
9.536743e-7
*Main> test1 0.01
2.2888184e-5
*Main> test1 0.001
2.4414063e-4
*Main> test1 0.0001
-3.7109375e-2
*Main>

现在我很困惑.我看不到为什么这里必须涉及数字问题.折叠本质上是如何收集在两种情况下都应该相同的每个元素,对吗?

Now I am confused. I can't see why numerical issues has to be involved here. Fold are essentially how ones collect each element which should be same in both cases, right?

推荐答案

通常,添加浮点值的 order 很重要.自己研究的切入点可以是 http://en.wikipedia.org/wiki/Loss_of_significance .总结一下基本警告,以一种过于简化的形式:

In general, the order in which floating point values are added is important. An entry point for own research could be http://en.wikipedia.org/wiki/Loss_of_significance . To summarize the basic caveat, in an oversimplified form:

由于有效位数有限,您必须假设类似

Due to the limited number of significant bits, you have to assume something like

 100000000000000000.0 + 1.0 = 100000000000000000.0

浮点计算中的

.因此,在计算时

in floating-point computations. Consequently, when computing

  100000000000000000.0
+                  1.0
- 100000000000000000.0

结果将为0.0-因此与

  100000000000000000.0
- 100000000000000000.0
+                  1.0

,结果将为1.0.

这篇关于Haskell中的foldl和folder的数值问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 04:23