This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 7 years ago.
As I was debugging my VBA code, I came across this weird phenomenon:
This loop
Dim x,y as Double
x = 0.7
y = 0.1
For x = x - y To x + y Step y
Next x
runs only twice!
I tried many variations of this code to nail down the problem, and here is what I came up with:
Replacing the loop boundaries with simple numbers (0.6 to 0.8) - helped.
Replacing variables with numbers (all the combinations) - didn't help.
Replacing the for-loop with do while/until loops - helped.
Replacing the values of x and y (y=0.01, 0.3, 0.4, 0.5, 0.7, 0.8, 0.9 - helped. 0.2, 0.6 -didn't help. x=1, 2 ,3 helped. x=4, 5, 6, 7, 8, 9 - didn't help.
Converting the Double to Decimal with CDec() - helped.
Using the Currency data type instead of Double - helped.
So what we have here is a floating-point rounding-error that happens on mysterious conditions.
What I'm trying to find out is what are those conditions, so we can avoid them.
Who will unveil this mystery?
(Pardon my English, it's not my mother tongue).
GD Falcon,
Generally in solving a For...Next loop it would not be advisable to use 'double' or 'decimal' or 'currency' variables as they provide a level of uncertainty in their accuracy, it's this level of inaccuracy that is wrecking havoc on your code as the actual stop parameter (when x-y, plus (n x y) = x+y) is, in terms of absolutes, an insolvable equation unless you limit the number of decimals it uses.
It is generally considered better practice to use integers (or long) variables in a For...Next loop as their outcome is more certain.
See also below post:
How to make For loop work with non integers
If you want it to run succesfully and iterate 3 times (as I expect you want)
Try like below:
Dim x, y As Double
x = 0.7
y = 0.1
For x = Round(x - y, 1) To Round(x + y, 1) Step Round(y, 1)
Debug.Print x
Next x
Again, it is better not to use Doubles in this particular way to begin with but if you must you would have to limit the number of decimals they calculate with or set a more vague end point (i.e. x > y, rather than x = y)
The coding you use implies that you wish to test some value x against a tolerance level of y.
Assuming this is correct it would imply testing 3 times where;
test_1: x = x - y
test_2: x = x
test_3: x = x + y
The below code would do the same but it would have a better defined scope.
Dim i As Integer
Dim x, y, w As Double
x = 0.7
y = 0.1
For i = -1 To 1 Step 1
w = x + (i * y)
Debug.Print w
Next i
Good luck !
Related
These are the conditions:
if(x > 0)
{
y >= a;
z <= b;
}
It is quite easy to convert the conditions into Linear Programming constraints if x were binary variable. But I am not finding a way to do this.
You can do this in 2 steps
Step 1: Introduce a binary dummy variable
Since x is continuous, we can introduce a binary 0/1 dummy variable. Let's call it x_positive
if x>0 then we want x_positive =1. We can achieve that via the following constraint, where M is a very large number.
x < x_positive * M
Note that this forces x_positive to become 1, if x is itself positive. If x is negative, x_positive can be anything. (We can force it to be zero by adding it to the objective function with a tiny penalty of the appropriate sign.)
Step 2: Use the dummy variable to implement the next 2 constraints
In English: if x_positive = 1, then y >= a
However, if x_positive = 0, y can be anything (y > -inf)
y > a - M (1 - x_positive)
Similarly,
if x_positive = 1, then z <= b
z <= b + M * (1 - x_positive)
Both the linear constraints above will kick in if x>0 and will be trivially satisfied if x <=0.
I currently am going through some examples of J, and am trying to do an exponential moving average.
For the simple moving average I have done as follows:
sma =: +/%[
With the following given:
5 sma 1 2 3 4 5
1.2 1.4 1.6 1.8 2
After some more digging I found an example of the exponential moving average in q.
.q.ema:{first[y]("f"$1-x)\x*y}
I have tried porting this to J with the following code:
ema =: ({. y (1 - x)/x*y)
However this results in the following error:
domain error
| ema=:({.y(1-x) /x*y)
This is with x = 20, and y an array of 20 random numbers.
A couple of things that I notice that might help you out.
1) When you declare a verb explicitly you need to use the : Explicit conjunction and in this case since you have a dyadic verb the correct form would be 4 : 'x contents of verb y' Your first definition of sma =: +/%[ is tacit, since no x or y variables are shown.
ema =: 4 : '({. y (1 - x)/x*y)'
2) I don't know q, but in J it looks as if you are trying to Insert / a noun 1 - x into a list of integers x * y. I am guessing that you really want to Divides %. You can use a gerunds as arguments to Insert but they are special nouns representing verbs and 1 - x does not represent a verb.
ema =: 4 : '({. y (1 - x)%x*y)'
3) The next issue is that you would have created a list of numbers with (1 - x) % x * y, but at that point y is a number adjacent to a list of numbers with no verb between which will be an error. Perhaps you meant to use y * (1 - x)%x*y ?
At this point I am not sure what you want exponential moving average to do and hope the clues I have provided will give you the boost that you need.
can someone please explain the following to me?
Sub TestCalc()
Dim Z As Double
Dim Y As Double
Dim X As Integer
Dim W As Double
Dim V As Double
X = 44 / 14 ' returns 3
Z = (0.14 * 14) ' returns 1.96
Y = ((44 / 14) - (44 \ 14)) * 14 ' returns 2 SHOULD RETURN 1.96
W = (44 / 14) - X ' returns 0.142857142857143
V = W * 14 ' returns 2 SHOULD RETURN 1.96
End Sub
1.96 is the value that I would expect to get from the code. However, I only get this value when I use hard coded values. If I work with variables it rounds it up and returns the value 2 (Y or V). I'm need to understand why, as 1.96 is that value that I expect to be returned. I need to ensure that it performs this calculation correctly to ensure that my math formula functions properly in my main procedure
Your expectations are incorrect.
0.14 * 14 = 1.96; however, W is 0.142857142857143 - that value * 14 = 2.
I am guessing that there are some unseen conditions determining if the numbers you are entering are being calculated as integers or doubles. What happens when you type out Y as
Y = ((44.0 / 14.0) - (44.0 \ 14.0)) * 14.0
or however you can specify doubles in Visual Basic.
Also the bottom of this article mentions a mode that warns you when unsafe conversions take place which might help track it down.
https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/operators-and-expressions/arithmetic-operators
I know similar questions have been answered before but none of the answers I could find were specific to .NET.
Does the VB.NET compiler optimize expressions like:
x = y / 4
by compiling:
x = y * 0.25
And before anyone says don't worry the difference is small, i already know that but this will be executed a lot and choosing one over the other could make a useful difference in total execution time and will be much easier to do than a more major refactoring exercise.
Perhaps I should have mentioned for the benefit of those who live in an environment of total freedom: I am not at liberty to change to a different language. If I were I would probably have written this code in Fortran.
As suggested here is a simple comparison:
Dim y = 1234.567
Dim x As Double
Dim c = 10000000000.0
Dim ds As Date
Dim df As Date
ds = Now
For i = 1 To c
x = y / 4
Next
df = Now
Console.WriteLine("divide " & (df - ds).ToString)
ds = Now
For i = 1 To c
x = y * 0.25
Next
df = Now
Console.WriteLine("multiply " & (df - ds).ToString)
The output is:
divide 00:00:52.7452740
multiply 00:00:47.2607256
So divide does appear to be slower by about 10%. But this difference is so small that I suspected it to be accidental. Another two runs give:
divide 00:00:45.1280000
multiply 00:00:45.9540000
divide 00:00:45.9895985
multiply 00:00:46.8426838
Suggesting that in fact the optimization is made or that the arithmetic operations are a vanishingly small part of the total time.
In either case it means that I don't need to care which is used.
In fact ildasm shows that the IL uses div in the first loop and mul in the second. So it doesn't make the subsitution after all. Unless the JIT compiler does.
How do I use Excel VBA to find the minimum value of an equation?
For example, if I have the equation y = 2x^2 + 14, and I want to make a loop that will slowly increase/decrease the value of x until it can find the smallest value possible for y, and then let me know what the corresponding value of x is, how would I go about doing that?
Is there a method that would work for much more complicated equations?
Thank you for your help!
Edit: more details
I'm trying to design a program that will find a certain constant needed to graph a nuclear decay. This constant is a part of an equation that gets me a calculated decay. I'm comparing this calculated decay against a measured decay. However, the constant changes very slightly as the decay happens, which means I have to use something called a residual-square to find the best constant to use that will fit the entire decay best to make my calculated decay as accurate as possible.
It works by doing (Measured Decay - Calculated Decay) ^2
You do that for the decay at several times, and add them all up. What I need my program to do is to slowly increase and decrease this constant until I can find a minimum value for the value I get when I add up the residual-squared results for all the times using this decay. The residual-squared that has the smallest value has the value of the constant that I want.
I already drafted a program that does all the calculations and such. I'm just not sure how to find this minimum value. I'm sure if a method works for something like y = x^2 + 1, I can adapt it to work for my needs.
Test the output while looping to look for the smallest output result.
Here's an Example:
Sub FormulaLoop()
Dim x As Double
Dim y As Double
Dim yBest As Double
x = 1
y = (x ^ 2) + 14
yBest = y
For x = 2 To 100
y = (x ^ 2) + 14
If y < yBest Then
yBest = y
End If
Next x
MsgBox "The smallest output of y was: " & yBest
End Sub
If you want to loop through all the possibilities of two variables that make up x then I'd recommend looping in this format:
Sub FormulaLoop_v2()
Dim MeasuredDecay As Double
Dim CalculatedDecay As Double
Dim y As Double
Dim yBest As Double
MeasuredDecay = 1
CalculatedDecay = 1
y = ((MeasuredDecay - CalculatedDecay) ^ 2) + 14
yBest = y
For MeasuredDecay = 2 To 100
For CalculatedDecay = 2 To 100
y = ((MeasuredDecay - CalculatedDecay) ^ 2) + 14
If y < yBest Then
yBest = y
End If
Next CalculatedDecay
Next MeasuredDecay
MsgBox "The smallest output of y was: " & yBest
End Sub