|
|
comments (0)
|
On some rare occasion you may have a need to conditionally change the sign of a number. The most obvious way of doing this is
If x then y = -y
However there are a few occasions where you might want to do this without using a conditional, either in an Excel formula or in code. I wouldn't call this a best practice, merely a convenient trick to know about.
y = y * (x * 2 + 1)
Why does it work? Well in VB (and Excel) boolean true implicitly converts to integer -1 and boolean false converts to integer 0. So when True you have:y = y * (x * 2 + 1)
y = y * (-1 * 2 + 1)
y = y * (-2 + 1)
y = y * -1
Whereas when False you end up with:y = y * (x * 2 + 1)
y = y * (0 * 2 + 1)
y = y * (0 + 1)
y = y * 1
So there you have it. It's not always going to be the best way, but it's good to know about.
|
|
comments (0)
|
This may seem obvious to a lot of you, and if you have never made a mistake because of zero-based math and/or just don't care about that sort of thing, well.. you might as well just move along then :-)
Recently I was working with code that made extensive use of loops. While debugging it, I kept running across "one-off" errors that were causing boundary violations.
After a particularly enthralling session of fixes, I thought I would post a quickie on how to tell how many times your loop is going to calculate. Assuming a legal* executable loop, A loop will execute |(U - L) ÷ S| +1 times. Where U is the loop's upper-bound; L is the lower-bound; and S is the step. The pipes ("|") represent an integer value (Ex: 8 ÷ 5 =1.6 whereas |8 ÷5| = 1).
Explanation:
When you do division, say "16/4" you are essentially creating an imaginary number line from 0 to 16. (Yes Zero, wait for it.) You then start at 4 then count forward by fours (4,8,12,...) until the next hop will cause you to exceed 16. The number of hops is the result.
To get the number of iterations in a loop you are doing essentially the same thing... Expect you also count the first number of the line then begin your hops. Essentially, you count the Zero as a hop.
Example1:
VB:
For i = 0 To 16 Step 4
C#
for (int i =0; a<16; i+4)
Iterates 0,4,8,12,16.
Example2:
VB:
For i = -3 To 12 Step 5
C#
for (int i =-3; a<12; i+5)
Iterates: -3,2,7,12
*"Legal Loop": I am defining "legal" as a loop that a positive non-zero step, with an upper bound greater than the lower bound, and vice-versa if a negative step is used.