I am currently writing a program that contains a two dimensional newton raphson sub. it starts like this:
Sub newton11()
Dim x As Double, z As Double, tolerance As Double
Dim error_x As Double, error_z As Double
Dim iteration As Integer
iteration = 0
tolerance = 0.05
x = Range("h19").value
z = Range("h20").value
however when I run the sub, it doesn't work. When I was debugging I noticed when I hovered over x it was assigned a value of -344 when Range("h19") is 53 and z was assigned -5.12 when Range("20") is 0.
does anybody know how to fix this?
Always define the sheet where you pull the data from. If you write:
x = Range("H19").Value
by default you're saying:
x = ActiveSheet.Range("H19").Value
which is probably containing the value -344 while you were waiting for 53. With this:
x = Sheets("myGoodSheet").Range("H13").Value
you're sure you're referencing to the proper one. And as Mark says in his comment, even better if you reference the correct workbook with Workbooks(j) just in front of the Sheets collection.
What you're describing isn't possible.
Instead of this:
x = Range("h19").value
z = Range("h20").value
Extract variables:
Dim xRange As Range, yRange As Range
Set xRange = Range("h19")
Set yRange = Range("h20")
x = xRange.Value
y = yRange.Value
Now place a breakpoint on the x = xRange.Value line, and use the locals window (from the View menu) to inspect the runtime value of xRange and yRange - then F8 and inspect the runtime value of x: the two are the same.
See #Matteo's answer for the why.
Related
I am having trouble with some loops in some code that I have inherited but that I can't get to run. I have passed what I assume are the correct values into the function (see my previous question), but now I am struggling to have the initial loops work.
The function works fine when called in a cell. However, when it runs in this macro, it is giving me a few errors, which I have chased back to the ReDim of the Lambda and v variables.
When I check it in the debugger, Lambda has the value of 0.33, but the value of the variable Splines is 1, and there is no variable with the value 0.33 that it could be picking up nearby.
Meanwhile I would expect V to pick up the value of 2, i.e. 1+1, but instead it has the value of 0.
I cannot work out why this is happening. Here is the code.
Function Spline(form As String, Splines As Integer, params As Variant, knots As Variant, coef As Variant, tstar As Range) 'form is type of spline, splines is number of knots, params is gammas, knots as knot posititions, coef as 0, tstar as cycle length in days
Dim Lambda As Variant
Dim v As Variant
Dim kmin, kmax As Double
Dim vtstar As Variant
Dim vspline As Variant
Dim a As Long
vtstar = tstar.Value2 'set vtstar as second value of the array of the cycle length
ReDim vspline(1 To UBound(vtstar), 1 To 1) 'set vspline to be cycle lengths without the 0
For a = 1 To UBound(vtstar) 'for each cycle to the max cycle
If vtstar(a, 1) = 0 Then 'for each cycle
vspline(a, 1) = 1 'recoding the days cycles into cycle number
'Exit Function
GoTo Avert 'unsure of this functionality, i think its just part of the loop syntax, by the 'exit function notation
End If
timeS = Log(vtstar(a, 1)) 'set timeS as the log of the cycle length
ReDim Lambda(Splines, 0) 'set lambda to number of knots
ReDim v(Splines + 1, 0) 'recode v to number of knots plus 1
v(0, 0) = 1
v(1, 0) = timeS 'unsure about this part
This is causing errors when the lambda and v variables are used in calculations further down in the function, first causing the lambda calculations to give "subscript out of range" error when called in this loop, I assume because 0.33 isn't a cycle number:
For i = 1 To Splines 'loop for each variable in splines (number of knots)
Lambda(i, 0) = (kmax - knots(i + 1)) / ulamb 'calculate lambda as kmax - knots+1 divided by difference between max and min knot values
Next i
(kmax, knots and ulamb appear to be calculating correctly)
And then I am getting a Error2015 error on the following loop which uses v
s = Application.SumProduct(params, v) 'set s as multiply gammas by v
Thanks in advance
Unclear what your previous question was.
Struggle a bit with your description.
the value of the variable Splines is 1
Is Splines a constant = 1? You do not show how Splines is a variable but you state it is equal to the number of knots...
ReDim Lambda(Splines, 0) 'set lambda to number of knots
If Splines = 1, you are re-dimensioning Lambda to an array of size 2x1. So your array will hold two values.
For i = 1 To Splines 'loop for each variable in splines (number of knots)
Lambda(i, 0) = (kmax - knots(i + 1)) / ulamb 'calculate lambda as kmax - knots+1 divided by difference between max and min knot values
Next i
If Splines = 1 you are starting your loop at 1 and ending at 1... So your array Lambda(0, 0) is empty. You will have a value in Lambda(1, 0).
Numeric variables give
Run Time 6` error
It all seems to be related to the way Excel on MacOs handles these declarations. I find with Integer, Single, and Double if you do a division you get the error.
Dim x, y as double
x=2
y=2 'error 6
x=x/2
y=y/2 'error6
End Sub
If you put x and y in Watch window you will see they are not showing as Double; instead, x is displayed as Variant/String, y as String.
The Variant/String performs ok, the string does not.
MS Docs state that Dim x,y As Double will declare both to be doubles. Others, who I assume are on Windows, say not, that you must say Dim x As Double, y As Double; but in this case, even that does not work.
MacOs Excel Version 16.43
This is the correct syntax:
Dim x As Double
Dim y As Double
x = 2
y = 2
x = x / 2
y = y / 2
' No error.
I am working on a MonteCarlo simulation model and part of it is to calculate the following formula:
X = Sqr(1-p)Y + Sqr(p)Z,
Where:
Y and Z are randomly obtained values based (idiosyncratic and systematic factors, respectviely) on a standard normal (inv.) distribution, calculated as:
Application.WorksheetFunction.NormInv (Rnd(), mean, sd)
p represents a correlation factor.
My aim is to square root a recalled formula, however when I try the following (inserting the first Sqr), it does not work and gives an error:
Matrix (n, sims) = (R * Sqr(Application.WorksheetFunction.NormInv(Rnd(), mean, sd))) + (Sqr(1 - R) * RandomS(s, x))
where:
R: Correlation factor
RandomS(s,x): generated matrix with Z values.
I don't want to go into too much details about the background and other variables, as the only problem I am getting is with Square Rooting the equation.
Error message I recieve reads:
Run-time error '5':
Invalid procedure call or argument
When I click debug it takes me to the formula, therefore there must be something wrong with the syntax.
Can you help with directly squaring the formula?
Thank you!
Andrew
Square root is simply Sqr.
It works fine in Excel VBA, so for example:
MsgBox Sqr(144)
...returns 12.
Just don't confuse it with the syntax for a worksheet function with is SQRT.
If you're still having an issue with your formula, tit must be with something other than the Square Root function, and I'd suggest you check the values of your variable, and make sure they are properly declared (preferably with Option Explicit at the top of the module).
Also make sure that you're passing Sqr a positive number.
Documentation: Sqr Function
I'm not a math major, but with your formula:
X = Sqr(1-p)Y + Sqr(p)Z,
...you specified how Y and Z are calculated, so calculate them separately to keep it simple:
Dim X as Double, Y as Double, Z as Double
Y = Application.WorksheetFunction.NormInv (Rnd(), mean, sd)
Z = Application.WorksheetFunction.NormInv (Rnd(), mean, sd)
Assuming the comma is not supposed to be in the formula, and having no idea what p is, your final code to calculate X is:
X = Sqr(1-p) * Y + Sqr(p) * Z
Public Function foo()
Dim x As Double, y As Double, z As Double
x = 1.26
y = 3.175
z = Round(x + y, 2)
foo = z
End Function
Running Excel 2007 on Windows 7. This function returns 4.43 into a cell with =foo() which is annoying as I want 4.44. I found some documentation claiming VBA ROUND uses even rounding but here the last digit is odd. What is wrong here?
You can always use the Worksheet Round Function instead of VBA's built-in one
Public Function foo2()
Dim x As Double, y As Double, z As Double
x = 1.26
y = 3.175
z = Application.WorksheetFunction.Round(x + y, 2)
foo2 = z
End Function
foo2 will result in 4.44 (tested on my machine). I don't know if this would affect performance at all.
You will need to use decimal types to accomplish this which uses integer based arithmetic as opposed to floating point based.
Excel doesn't have a native data type for this, so you have to use a Variant and then convert to a decimal using the CDec function.
Public Function foo()
Dim x As Variant, y As Variant, z As Variant
x = CDec(1.26)
y = CDec(3.175)
z = Round(x + y, 2)
foo = z
End Function
While Excel.WorksheetFunction.Round does perform correct 4/5 rounding, it is terribly slow and, of course, requires Excel to be installed.
For fast and precise rounding of any value - up, down, 4/5, Banker's, significant digits, Base 2 or Base 10, and more - go to my project VBA.Round.
I am trying to generate titles automatically in Gnuplot. I have an array (titleprefix) and another set of variables (a1,a2,a3...), and the title is the prefix followed by the slope (the a's). I tried this:
title(n) = sprintf("word(titleprefix,n).sprintf(\" Slope = %.3f\",%f)",a."n"+0)
Of course that did not work. Error is:
Non-numeric string found where a numeric expression was expected.
Any idea how I solve this?
Eventually, I would like to plot several curves like this:
plot f1 w l t title(1), \
f2 w l t title(2), \
f3 w l t title(3)
One option to do such things is to build the complete set title command inside such a function and then eval that.
In your case it requires a bit of brain twisting to get the quotes correct, so that the variable names are correct:
titleprefix="first second third"
a1 = 1.111
a2 = 2.222
a3 = 3.333
title(n) = 'set title "'.word(titleprefix, n).': ".sprintf("Slope = %.3f", a'.n.')'
set multiplot layout 1,3
eval(title(1))
plot x
eval(title(2))
plot 2*x
eval(title(3))
plot 3*x
unset multiplot
Alternatively, you can construct a word list of the formatted variable values when you define or calculate the variables.
a1 = 1.111111
a2 = 2.222222
a3 = 3.333333
tmp = 'a = ""'
do for [i=1:3] { tmp = tmp.".sprintf('%.3f ', a".i.")" }
eval(tmp)
plot for [i=1:3] i*x title word(a, i)