1 Replies - 2371 Views - Last Post: 24 February 2011 - 04:36 PM Rate Topic: -----

#1 soundtrackseven  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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

			'Add to previous value
			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  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1