Stupid Monte Carlo

據說現在已經沒有人用手計 Integration 。記得以前 A. Maths 計過很多,多數是 indefinite integral ,當年是完全不會計的。但是我去考會考時,將題目照抄一次在答題薄都有個 E 合格。學術人生,時至今天都是乎碌撞棍。

假設你要計這樣的東西:

int x3

minimum = 1, maximum = 3

如果用手計的話,就是先求其 antiderivative (F)。如果我的 A.Maths 仍然 valid 的話,F 就是 (x4)/4 + C 吧。之後再將 3 和 1 塞入 x 再相減1,即是 (34)/4 – (14)/4 = 20.
如果你相當無聊的話,係可以叫電腦產生 n 個 1 至 3 的亂數,再塞入 x3 n 次。所有 n 個計算結果計其平均值。再將此 mean 值乘以 max 及 min 的差,是可得 Integral 的近似值。
在 R ,如果要產生 n 個一般亂數( Uniform distribution 的亂數),可用 runif 的 function ,例如要產生 10000 個 1-3 之間的亂數:

runif(100000, min=1,max=3)

要計出上面的 definite integral 方法是:

# chew that < -
x<- runif(100000, min=1,max=3)
2*mean(x**3)

為何 mean 要乘 2 ,是因為 max – min = 2 。我求出的數字是 20.00751 ,與手計的 20 近似。當然, int 一次的話手計可能快過用機器模疑。但如果 int 了幾次的話,用這種方法求近似值會較快。

  1. 即F(max) – F(min) []

Today on history:

  1. 2009:  Paradox of fear II(3)
  2. 2007:  令人失望的大結局:《無題》大結局(0)
  3. 2005:  嘩!大地震!(0)
  4. 2005:  你話我無厘頭,我話你訓醒on99(1)
  5. 2003:  6xx(0)
  6. 2002:  Ballistic Birthday(0)

Comments 2

  1. passerby wrote:

    It’s called Monte-Carlo integration, right?

    Posted 23 Jul 2010 at 3:05 pm
  2. Chainsaw Riot wrote:

    @passerby: Yes, but the actual Monte-carlo integration can optimize to give a much more accurate integral then this.

    Posted 23 Jul 2010 at 3:25 pm

Post a Comment

Your email is never published nor shared. Required fields are marked *

Comments will be closed on October 19, 2010.