Hi I am getting the following error when computing GMT Time using nanoseconds as a long.
System.OverflowException: 'Arithmetic operation resulted in an overflow.'
Is there another data type that would work better with big values?
Private Sub gmtime(ByVal iSeconds As Object, ByVal iNanoseconds As Long, ByRef Timestamp As String)
Dim time As Object
Dim islpyr, lpcnt As Long
Dim t As Object
Dim i As Object
Dim ystart As Long
Dim y As Long
Dim sph As Object 'seconds per hour
Dim spd As Object 'seconds per day
Dim spy As Object 'seconds per year
Dim tm_sec As Long
Dim tm_min As Long
Dim tm_hour As Long
Dim tm_mday As Long
Dim tm_mon As Long
Dim tm_year As Long
Dim tm_wday As Long
Dim tm_yday As Long
Dim tm_isdst As Long
Dim mons(11) As Long
Dim temp As Object
Dim iMicroSeconds As Long
Dim iZeroCount As Long
Dim strZero As String
Dim strMicro As String
Dim iMicroData As Long
mons(0) = 31
mons(1) = 28
mons(2) = 31
mons(3) = 30
mons(4) = 31
mons(5) = 30
mons(6) = 31
mons(7) = 31
mons(8) = 30
mons(9) = 31
mons(10) = 30
mons(11) = 31
sph = CDec(60 * 60)
spd = CDec(24 * sph)
spy = CDec(365 * spd + 6 * sph) 'a year is about 365.25 days
tm_isdst = 0
time = CDec(iSeconds)
If time < 0 Then
time = time * (-1)
End If
i = CDec(time)
i = Fix(i / spd) Mod 7 + 4
While i >= 7
i = i - 7
End While
tm_wday = i
temp = Fix(time / spd)
temp = temp * spd
i = time - temp
tm_hour = Fix(i / sph) Mod 24
tm_min = Fix(i / 60) Mod 60
tm_sec = i Mod 60
y = Fix(time / spy)
y = y + 370
time = Fix(time / spd)
Do
islpyr = 0
If ((y Mod 4) = 0) And (((y Mod 100) <> 0) Or ((y Mod 400) = 0)) Then
islpyr = 1
End If
lpcnt = Fix(y / 4)
lpcnt = lpcnt - Fix(y / 100)
lpcnt = lpcnt + Fix(y / 400)
lpcnt = lpcnt - 89
ystart = (y - 370) * 365 + lpcnt
If ystart > time Then
y = y - 1
End If
Loop While ystart > time
time = time - ystart
If time = 365 Then
time = 0
y = y + 1
End If
If islpyr Then
time = time + 1
End If
tm_yday = time
time = time + 1
For i = 0 To 10
t = mons(i)
If (i = 1) And (islpyr = 1) Then
t = t + 1
End If
If time <= t Then
Exit For
End If
time = time - t
Next i
tm_year = y - 300 + 1900
tm_mon = i + 1
tm_mday = time
strZero = "."
iZeroCount = 6
iMicroSeconds = Fix(iNanoseconds / 1000)
iMicroData = iMicroSeconds
While iMicroSeconds <> 0
iMicroSeconds = Fix(iMicroSeconds / 10)
If (iMicroData Mod 10) = 0 Then
iMicroData = iMicroSeconds
End If
If iZeroCount <> 0 Then
iZeroCount = iZeroCount - 1
End If
End While
For i = 1 To iZeroCount
strZero = strZero + "0"
Next i
If Fix(iNanoseconds / 1000) <> 0 Then
strMicro = strZero + CStr(Fix(iNanoseconds / 1000))
Else
strMicro = strZero
End If
Timestamp = CStr(tm_year) + "-" + CStr(tm_mon) + "-" + CStr(tm_mday) + " " + CStr(tm_hour) + ":" + CStr(tm_min) + ":" + CStr(tm_sec) + strMicro
End Sub
It wouldn't let me add the code as the post is mostly code. The nanoseconds values are coming from a waveform file and this function is used to process it into GMT time.
The function is called on a loop for each line of the file and returns this error mid-way through the loop.
The value is '1.5518651852110167E+270' when it hits the error
I'm sorry but there's no way to put a 10^270 number inside ANY variable.
The biggest variable for numbers is Long that holds:
signed 64-bit (8-byte) integers ranging in value from
-9,223,372,036,854,775,808 through 9,223,372,036,854,775,807
(9.2...E+18).
From Long DataType
I sueggest you to avoiding counting time in nanoseconds instead use seconds, minutes, or even days if your TimeSpan is too big.
Counting time in nanoseconds is pointless.
Remarks
If you couldn't avoid using nanoseconds because your file is in nanoseconds your only option is to convert you nanoseconds value in a DateTime format on every line and hope that the value will be shorter than 9.2E+18
Otherwise you could use a BigInteger and use it to calculate a DateTime for every line of your file.
Just for the curiosity: You would need a 896 bytes unsigned DataType to store a 1.5*10^270 inside it.
Related
Found a function on Excelguru which I changed a few things in and gonna edit some more. The idea is to use this to register worked hours and minutes.
There is one thing in this I don't understand: if I type the wrong time in the column reff I get a msg that its wrong, but it wont disappear unless I click it 10 times. I cant see what Im doing wrong. The entire code is posted and Im grateful for any help.
Use his function as part of the formula in the sheet like: TimeValue($E2;$F2;"16:00";"18:00";B2;9;C2)
Function TimeValue(FromTime As String, ToTime As String, StartTime As String, StopTime As String, Optional Weekday As String, Optional Daynr As Integer, Optional Holiday As String)
Dim x As Long
Dim F As Double
Dim T As Double
Dim Start As Double
Dim Stopp As Double
Dim Min As Long
Dim Day As Integer
Dim OverMid As Boolean
Select Case LCase(Weekday)
Case "mandag"
Day = 1
Case "tirsdag"
Day = 2
Case "onsdag"
Day = 3
Case "torsdag"
Day = 4
Case "fredag"
Day = 5
Case "lordag"
Day = 6
Case "sondag"
Day = 7
Case "x"
Day = 8
Case Else
Day = 0
End Select
OverMid = False
If LCase(Holiday) = "x" Then Day = 8
If Len(FromTime) = 0 Or Len(ToTime) = 0 Then
Exit Function
End If
If Len(FromTime) <> 5 Then
MsgBox ("Use format TT:MM - From time is wrong:" & FromTime)
Exit Function
End If
If Len(ToTime) <> 5 Then
MsgBox ("Use format TT:MM - To time is wrong:" & ToTime)
Exit Function
End If
F = Val(Left(FromTime, 2)) * 60 + Val(Right(FromTime, 2))
T = Val(Left(ToTime, 2)) * 60 + Val(Right(ToTime, 2))
Start = Val(Left(StartTime, 2)) * 60 + Val(Right(StartTime, 2))
Stopp = Val(Left(StopTime, 2)) * 60 + Val(Right(StopTime, 2))
If T = 0 Then T = 24 * 60
If T < F Then
T = T + 24 * 60
OverMid = True
End If
If Stopp = 0 Then Stopp = 24 * 60
For x = F + 1 To T
If x > Start And x <= Stopp Then
Min = Min + 1
End If
Next x
If OverMid = True Then
For x = 0 To Val(Left(ToTime, 2)) * 60 + Val(Right(ToTime, 2))
If x > Start And x <= Stopp Then
Min = Min + 1
End If
Next x
End If
'If weekday is set, equal to day
If Daynr <> 0 Then
If Daynr <> 9 Then
If Day <> Daynr Then Min = 0
End If
If Daynr = 9 And (Day > 5) Then
Min = 0
End If
End If
TimeValue = Min / 60
End Function
And the sub in the sheets
Private Sub Worksheet_Change(ByVal Target As Range)
Dim streng As String
Dim k As Long
Dim r As Long
k = Target.Column
r = Target.Row
If Cells(1, k) = "P" Then
If Cells(r, k) = "x" Then
Cells(r, 4) = "x"
Else
Cells(r, 4) = ""
End If
End If
End Sub
Message boxes really don't belong in UDFs (VBA functions meant to be used as spreadsheet functions).
Instead of the message box you could use code like:
If Len(FromTime) <> 5 Then
TimeValue = "Error! Use format TT:MM - From time is wrong:" & FromTime
Exit Function
Or perhaps:
If Len(FromTime) <> 5 Then
TimeValue = CVErr(xlErrValue)
Exit Function
This later will cause #VALUE! to display in the cell. Include enough documentation in your spreadsheet so that users can interpret such error values.
I am working an MS Access application a part of which uses Beta Distribution function. Since MS Access does not have Beta Distribution function of its own I'm using calling BetaDist function from MS Excel. I've tested the code in MS Excel and it seems to run successfully. In MS Access also the code is working fine and generating correct results but the time taken by Access is very high than the time taken by Excel. I'm posting the part of code which utilizes BetaDist function and also the slowest portion of the code. I want to reduce the time taken by Access. Any help is appreciated.
Part of Code which utilizes BetaDist:
For i = 1 To UBound(arrBetaParam)
If arrBetaParam(i).Alpha <= 0 Or arrBetaParam(i).Beta <= 0 Or tryOutValue > arrBetaParam(i).ExpValue Then
dblTempEP = 0
Else
If tryOutValue > arrBetaParam(i).LastKnownGoodValue Then
dblTempEP = 0
Else
dblTempEP = 1
End If
Dim bt As Double
bt = -1
On Error Resume Next
bt = Excel.WorksheetFunction.BetaDist(tryOutValue, arrBetaParam(i).Alpha, arrBetaParam(i).Beta, 0, arrBetaParam(i).ExpValue)
tj = bt
If bt > -1 Then
If bt > 1 Then bt = 1
If bt < 0 Then bt = 0
arrBetaParam(i).LastKnownGoodValue = tryOutValue
dblTempEP = 1 - bt
End If
On Error GoTo 0
End If
OEP = OEP + dblTempEP * arrBetaParam(i).Rate
'sumRate = sumRate + arrBetaParam(i).Rate
Next
Your code is probably taking so long due to the fact it has to open the Excel application.
BetaDist is not complicated to implement. Why not create a VBA function in Acces VBA. Here is the formula:
f(x) = B(alpha,beta)-1 xalpha-1(1-x)beta-1
Here I found a decent implementation. Didn't test it though:
Option Explicit
Const n As Long = 200 ' increase for accuracy, decrease for speed
Public aa As Double
Public bb As Double
Function BetaDist1(x As Double, a As Double, b As Double)
Dim d1 As Double
Dim d2 As Double
Dim n1 As Long
Dim n2 As Long
aa = a
bb = b
n1 = x * n
n2 = n - n1
d1 = SimpsonInt(0, x, n1)
d2 = SimpsonInt(x, 1, n2)
BetaDist1 = d1 / (d1 + d2)
End Function
Function SimpsonInt(ti As Double, tf As Double, ByVal n As Long) As Double
' shg 2006
' Returns the integral of Func (below) from ti to tf _
using Composite Simpson's Rule over n intervals
Dim i As Double ' index
Dim dH As Double ' step size
Dim dOdd As Double ' sum of Func(i), i = 1, 3, 5, 7, ... n-1, i.e., n/2 values
Dim dEvn As Double ' sum of Func(i), i = 2, 4, 6, ... n-2 i.e., n/2 - 1 values
' 1 + (n/2) + (n/2 - 1) + 1 = n+1 function evaluations
If n < 1 Then Exit Function
If n And 1 Then n = n + 1 ' n must be even
dH = (tf - ti) / n
For i = 1 To n - 1 Step 2
dOdd = dOdd + Func(ti + i * dH)
Next i
For i = 2 To n - 2 Step 2
dEvn = dEvn + Func(ti + i * dH)
Next i
SimpsonInt = (Func(ti) + 4# * dOdd + 2# * dEvn + Func(tf)) * dH / 3# ' weighted sum
End Function
Function Func(t As Double) As Double
Func = t ^ (aa - 1) * (1 - t) ^ (bb - 1)
End Function
You could do like this:
Dim xls As Excel.Application
Set xls = New Excel.Application
' Begin loop.
bt = xls.WorksheetFunction.BetaDist(tryOutValue, arrBetaParam(i).Alpha, arrBetaParam(i).Beta, 0, arrBetaParam(i).ExpValue)
' End loop.
xls.Quit
Set xls = Nothing
I have used below code to find average of 10 sample . But during first time it take sample and do the averaging . during next cycle counter not become Zero.and text box not updating
Static counter As Integer = 0
DIm average_sum As Double = 0
If counter < 10 Then
counter = counter + 1
Count_val.Text = counter
Dim array(10) As Double
For value As Integer = 0 To counter
array(counter) = k
average_sum = average_sum + array(counter)
Next
If counter = 10 Then
average_sum = average_sum / array.Count
System.Threading.Thread.Sleep(250)
Array_count.Text = average_sum
End If
If counter > 10 Then
average_sum = 0
counter = 0
End If
End If
If Avg_count < 10 Then
Dim array(10) As Double
For value As Double = 0 To Avg_count
array(Avg_count) = k
average_sum = average_sum + array(Avg_count)
Avg_count = Avg_count + 1
Next
If Avg_count = 10 Then
average_sum = average_sum / Avg_count
System.Threading.Thread.Sleep(250)
Average.Text = average_sum
Avg_count = 0
End If
End If
Here count value setting properly . But after 2 to3 cycle Average will done earlier itself same thing i writen in excel to compare averages but not matching with average and excel sheet data
Below is excel sheet code.Both code are in timer1 block.
If counter < 10 Then
'counter = 0
'average_sum = 0
Dim headerText = ""
Dim csvFile As String = IO.Path.Combine(My.Application.Info.DirectoryPath, "Current.csv")
If Not IO.File.Exists((csvFile)) Then
headerText = "Date,TIME ,Current, "
End If
Using outFile = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True)
If headerText.Length > 0 Then
outFile.WriteLine(headerText)
End If
Dim date1 As String = "25-10-2014"
Dim time1 As String = TimeOfDay()
Dim x As String = date1 + "," + time1 + "," + distance
outFile.Write(x)
End Using
End If
If counter > 10 Then
counter = 0
End If
Is there anybody know how to make normal distributed random number in vb.net?
thank you
From this forum post :
Usage:
GaussNumDist(Mean, Standard Deviation, Sample Size)
Code example below, which will populate GaussNumArray() with the sample of numbers, whose distribution will have the mean and standard deviation specified:
Imports System.Math
Module Module1
Friend GaussNumArray() As Double
Friend intICell As Long
Friend Function GaussNumDist(ByVal Mean As Double, ByVal StdDev As Double, ByVal SampleSize As Integer)
intICell = 1 'Loop variable
ReDim GaussNumArray(SampleSize)
Do While (intICell < (SampleSize + 1))
Call NumDist(Mean, StdDev)
Application.DoEvents()
Loop
End Function
Sub NumDist(ByVal meanin As Double, ByVal sdin As Double)
'---------------------------------------------------------------------------------
'Converts uniform random numbers over the region 0 to 1 into Gaussian distributed
'random numbers using Box-Muller algorithm.
'Adapted from Numerical Recipes in C
'---------------------------------------------------------------------------------
'Defining variables
Dim dblR1 As Double
Dim dblR2 As Double
Dim mean As Double
Dim var As Double
Dim circ As Double
Dim trans As Double
Dim dblY1 As Double
Dim dblY2 As Double
Dim Pi As Double
Pi = 4 * Atan(1)
'Get two random numbers
dblR1 = (2 * UniformRandomNumber()) - 1
dblR2 = (2 * UniformRandomNumber()) - 1
circ = (dblR1 ^ 2) + (dblR2 ^ 2) 'Radius of circle
If circ >= 1 Then 'If outside unit circle, then reject number
Call NumDist(meanin, sdin)
Exit Sub
End If
'Transform to Gaussian
trans = Sqrt(-2 * Log(circ) / circ)
dblY1 = (trans * dblR1 * sdin) + meanin
dblY2 = (trans * dblR2 * sdin) + meanin
GaussNumArray(intICell) = dblY1 'First number
'Increase intICell for next random number
intICell = (intICell + 1)
GaussNumArray(intICell) = dblY2 'Second number
'Increase intICell again ready for next call of ConvertNumberDistribution
intICell = (intICell + 1)
End Sub
Friend Function UniformRandomNumber() As Double
'-----------------------------------------------------------------------------------
'Outputs random numbers with a period of > 2x10^18 in the range 0 to 1 (exclusive)
'Implements a L'Ecuyer generator with Bays-Durham shuffle
'Adapted from Numerical Recipes in C
'-----------------------------------------------------------------------------------
'Defining constants
Const IM1 As Double = 2147483563
Const IM2 As Double = 2147483399
Const AM As Double = (1.0# / IM1)
Const IMM1 As Double = (IM1 - 1.0#)
Const IA1 As Double = 40014
Const IA2 As Double = 40692
Const IQ1 As Double = 53668
Const IQ2 As Double = 52774
Const IR1 As Double = 12211
Const IR2 As Double = 3791
Const NTAB As Double = 32
Const NDIV As Double = (1.0# + IM1 / NTAB)
Const ESP As Double = 0.00000012
Const RNMX As Double = (1.0# - ESP)
Dim iCell As Integer
Dim idum As Double
Dim j As Integer
Dim k As Long
Dim temp As Double
Static idum2 As Long
Static iy As Long
Static iv(NTAB) As Long
idum2 = 123456789
iy = 0
'Seed value required is a negative integer (idum)
Randomize()
idum = (-Rnd() * 1000)
'For loop to generate a sequence of random numbers based on idum
For iCell = 1 To 10
'Initialize generator
If (idum <= 0) Then
'Prevent idum = 0
If (-(idum) < 1) Then
idum = 1
Else
idum = -(idum)
End If
idum2 = idum
For j = (NTAB + 7) To 0
k = ((idum) / IQ1)
idum = ((IA1 * (idum - (k * IQ1))) - (k * IR1))
If (idum < 0) Then
idum = (idum + IM1)
End If
If (j < NTAB) Then
iv(j) = idum
End If
Next j
iy = iv(0)
End If
'Start here when not initializing
k = (idum / IQ1)
idum = ((IA1 * (idum - (k * IQ1))) - (k * IR1))
If (idum < 0) Then
idum = (idum + IM1)
End If
k = (idum2 / IQ2)
idum2 = ((IA2 * (idum2 - (k * IQ2))) - (k * IR2))
If (idum2 < 0) Then
idum2 = idum2 + IM2
End If
j = (iy / NDIV)
iy = (iv(j) - idum2)
iv(j) = idum
If (iy < 1) Then
iy = (iy + IMM1)
End If
temp = AM * iy
If (temp <= RNMX) Then
'Return the value of the random number
UniformRandomNumber = temp
End If
Next iCell
End Function
End Module
You can use following line
Dim x1 as Double = MathNet.Numerics.Distributions.Normal.Sample(MEAN, STDEV)
Math.Net Numeric package can be installed using following NuGet command
Install-Package MathNet.Numerics -Version 4.9.0
You can found more information on NuGet site
First off, here's my code:
Sub SimulatePortfolio()
Dim lambda As Double
Dim num As Integer
Dim cycles As Long
Column = 12
q = 1.5
lambda = 0.05
cycles = 100000
Dim data(1 To 100000, 1 To 10) As Integer
Dim values(1 To 10) As Double
For i = 1 To 10
values(i) = 0
Next i
temp = lambda
For i = 1 To cycles
lambda = temp
num = 10
t = 0
Dim temps(1 To 10) As Integer
For k = 1 To 10
temps(k) = 1000
Next k
Do While (t < 10 And num > 0)
t = t + tsim(lambda, num)
For j = 1 To 10
If (j > t) Then
temps(j) = temps(j) - 50
End If
Next j
num = num - 1
If (num <= 0) Then
Exit Do
End If
lambda = lambda * q
Loop
For l = 1 To 10
values(l) = values(l) + temps(l)
data(i, l) = temps(l)
Next l
Next i
For i = 1 To 10
Cells(i + 1, Column) = values(i) / cycles
'Problem occurs on this line:
Cells(i + 1, Column + 1).Value = Application.WorksheetFunction.Var(Application.WorksheetFunction.Index(data, i, 0))
Next i
End Sub
Function tsim(lambda As Double, num As Integer) As Double
Dim v As Double
Dim min As Double
Randomize
min = (-1 / lambda) * Log(Rnd)
For i = 1 To (num - 1)
Randomize
v = (-1 / lambda) * Log(Rnd)
If (min > v) Then
min = v
End If
Next i
tsim = min
End Function
When I set the value for cycles to 10000, it runs fine without a hitch. When I go to 100000 cycles, it gets an Error 13 at the indicated line of code.
Having been aware that Application.Tranpose is limited to 65536 rows with variants (throwing the same error) I tested the same issue with Index
It appears that Application.WorksheetFunction.Index also has a limit of 65536 rows when working with variants - but standard ranges are fine
So you will need to either need to dump data to a range and work on the range with Index, or work with two arrays
Sub Test()
Dim Y
Dim Z
'works in xl07/10
Debug.Print Application.WorksheetFunction.Index(Range("A1:A100000"), 1, 1)
Y = Range("A1:A65536")
`works
Debug.Print Application.WorksheetFunction.Index(Y, 1, 1)
'fails in xl07/10
Z = Range("A1:A65537")
Debug.Print Application.WorksheetFunction.Index(Z, 1, 1)
End Sub