|
楼主 |
发表于 2012-2-19 10:04:09
|
显示全部楼层
在EXCEL中用VBA实现模拟,代码如下:
Sub Macro1()
' 生成随机数,并处理
For i = 1 To 3000
' 生成随机数,添入到第一列
Cells(i, 1) = Rnd() - 0.5
t = Cells(i, 1)
' 处理随机数为1 -1,添入到第二列
If (t > 0) Then
Cells(i, 2) = 1
Else
Cells(i, 2) = -1
End If
Next i
' 第二列求和,填充到第三列
For i = 1 To 3000
t = 0
For j = 1 To i
t = Cells(j, 2) + t
Next j
Cells(i, 3) = t
Next i
' 用第三列数据绘制图形
Columns("C:C").Select
Charts.Add
ActiveChart.ChartType = xlLineMarkers
ActiveChart.SetSourceData Source:=Sheets("Sheet1").Range("C1:C3000"), PlotBy _
:=xlColumns
ActiveChart.Location Where:=xlLocationAsObject, Name:="Sheet1"
With ActiveChart
.HasTitle = False
.Axes(xlCategory, xlPrimary).HasTitle = False
.Axes(xlValue, xlPrimary).HasTitle = False
End With
End Sub
为了提高程序运行效率,修改上面代码如下:
Sub Macro1()
' 生成随机数,并处理
For i = 1 To 3000
' 生成随机数,添入到第一列
Cells(i, 1) = Rnd() - 0.5
t = Cells(i, 1)
' 处理随机数为1 -1,添入到第二列
If (t > 0) Then
Cells(i, 2) = 1
Else
Cells(i, 2) = -1
End If
If (i = 1) Then
Cells(1, 3) = Cells(1, 2)
Else
Cells(i, 3) = Cells(i - 1, 3) + Cells(i, 2)
End If
Next i
' 用第三列数据绘制图形
Columns("C:C").Select
Charts.Add
ActiveChart.ChartType = xlLineMarkers
ActiveChart.SetSourceData Source:=Sheets("Sheet1").Range("C1:C3000"), PlotBy _
:=xlColumns
ActiveChart.Location Where:=xlLocationAsObject, Name:="Sheet1"
With ActiveChart
.HasTitle = False
.Axes(xlCategory, xlPrimary).HasTitle = False
.Axes(xlValue, xlPrimary).HasTitle = False
End With
End Sub |
|