# Monte Carlo Integration

Page 1 of 1

## 1 Replies - 6450 Views - Last Post: 24 February 2011 - 04:36 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=140574&amp;s=ede58d47f29d18d5c04b68307e4999d0&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 soundtrackseven

Reputation: 0
• Posts: 3
• Joined: 21-October 09

# Monte Carlo Integration

Posted 21 November 2009 - 01:15 AM

This is actually a project in my programming class. We're supposed to use the Monte Carlo Integration method to calculate the approximate integral of the function x^2 + 2x + 1. So the form for this has four textboxes: one for each of the end of the interval, one for the number of simulation times, and one for the approximation/result when I click the button to calculate. Here's the code:

```Private Sub btnMCS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMCS.Click

Dim a As Integer
Dim b As Integer
Dim x As Double
Dim func As Double
Dim total As Double
Dim result As Double
Dim j As Integer
Dim N As Integer

a = txtboxA.Text
b = txtboxB.Text
N = txtboxST.Text

For j = 1 To N

'Generate a new number between a and b
x = (b - a) * Rnd()

'Evaluate function at new number
func = (x ^ 2) + (2 * x) + 1

total = total + func

Next j

result = (total / N) * (b - a)
txtboxApprox.Text = result

End Sub
```

I tried the code and it works for the interval [1,0]. I tried other intervals, and it doesn't work right. What did I do wrong? Any help is appreciated.

Is This A Good Question/Topic? 0

## Replies To: Monte Carlo Integration

### #2 BigGreen

Reputation: 0
• Posts: 13
• Joined: 28-January 11

## Re: Monte Carlo Integration

Posted 24 February 2011 - 04:36 PM

okay I really am not an expert at VB since I am barely learning how to use it but I am pretty sure that you need to insert a Val() in "txtboxA.Text" so it can look like this:

a = Val(txtboxA.Text)
b = Val(txtboxB.Text)
N = Val(txtboxST.Text)

Also im pretty sure that you need to convert your "result" into a string since you are adding more than one item. So it looks like this:

txtboxApprox.Text = Str(result)

IDK if this will help solve your problem or not but I hope that it does. If you can reply back letting me know whether the info I gave you helped you solve your problem or not would be greatly appreciated since how I mentioned to you before I am learning how to use VB and I wouldn't want to have info that is not correct. Thank you very much and I hope I was of some help.

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }