使用Haskell计算曲线面积?

时间:2016-04-10 15:47:47

标签: haskell

我想计算面积对于给定曲线y = f(x)在极限l和r之间。

  Input will be : l r [a1,a2,a3..] [b1,b2,b3,b4,..]
  The curve will be (a1)x^(b1) + (a2)x^(b2)+....

我的节目:

  area_curve _ _ [] [] = 0 
  area_curve l r (ai:as) (bi:bs) = (ai(r^^(bi+1)-l^^(bi+1))) + area_curve l r as bs 

当我运行程序时,我收到以下错误:

"ghci> " area_curve 1 4 [1,2,3,4,5] [6,7,8,9,10]
<interactive>:20:1:
    Non type-variable argument in the constraint: Num (a1 -> a)
    (Use FlexibleContexts to permit this)
    When checking that ‘it’ has the inferred type
      it :: forall a a1. (Fractional a1, Num a, Num (a1 -> a)) => a

1 个答案:

答案 0 :(得分:1)

分解为简单的作品

powers x = map (x^)
dot = zipWith (*)
minus = zipWith (-)

curve x as ps = dot as $ powers x ps

areacurve le ri as ps = minus (curve ri as ps) (curve le as ps)

<强>更新 请注意,我只是重构了你的代码,并没有真正研究它的作用。如果你想评估曲线的积分,这里是一种更有条理的方式

假设权力是非负的,我会通过将数字类型固定为Double来简化它,但应该很容易概括

type Curve = [(Double,Double)]

parabola = [(1.0,2.0)] 
line     = [(1.0,1.0)] 
zero     = []  

integral :: Curve -> Curve
integral = map (\(a,p) -> (a/(p+1),p+1))

eval :: Double -> Curve -> Double
eval :: Double -> Curve -> Double
eval x c = sum $ map (\(a,p) -> a*x**p) c

现在例如3*x^2+1

2<x<3曲线下面积
> curve = [(1.0,1.0),(3.0,2.0)]
> integral curve
[(0.5,2.0),(1.0,3.0)]

>  map ($ integral curve) $ map eval [2,3]
[10.0,31.5]

该区域是这两个值之差21.5

同样,您可以定义两条曲线之间的区域。