Math Question

Thesolis

Member
Joined
Apr 22, 2009
Messages
16
Programming Experience
1-3
Hi all,

Here's what's happening:
I have a counter that increments by 1 and then checks some frequencies to see if it should trigger at that time.
The problem is, my check is in the form of "If Math.Round(intCounter Mod Frequency) = 0 Then ..."
This works fine for nice numbers, but when the frequency is, let's say, 100/3, then things don't work out quite right.
The program triggers on 67 and 100, but not on 33 because 33.33333... > 33 and 33 Mod 100/3 is not close to 0.
I can get it to trigger on 33 by rounding first, but that also means that the program will trigger on 66 and 99 instead of
67 and 100, which is what it should do.

Any suggestions?

Thanks.
 
Last edited:
How are you rounding it out? 66.6 should round out to 67, not to 66.

The frequency is constant. In the example, it's always 33.33333.... . That means when I use the "Mod" command with Math.Round() I get, at t=67, Math.Round(67 Mod 33.33333......) which rounds to 0. The problem is, at t = 33, I get Math.Round(33 Mod 33.3333..) which is not close to 0 and therefore, does not trigger.
 
Can you explain the real world problem you are trying to solve with this code? Because to me dividing a counter by a frequency doesn't make much sense...
 
What he said. Trying to tally fractional values with integer counts just doesn't make any sense, even less so when those values are actually inexpressible in decimals. Even the most accurate timepiece cannot exactly match a frequency of 3 events per 100 ticks. From that point of view 33, 66, 99 is no less 'correct' than 33, 67, 100 or 34, 67, 100 and in any event Mod 33.3333 is utterly meaningless in real terms, which is why you'll never get 'correct' values using Round or any other function.
 
The problem here is precision. Use a counter which increases by step of 0.1 or 0.01 instead of 1; let us say a decimal counter. For example, suppose your counter increases with a 0.1 step. Using "If Math.Round(decCounter Mod Frequency) = 0 Then ...", it will tick as soon as decCounter reaches 33.4. Then you could round it to 33, if you really need an integer. It will tick again when decCounter reaches 66.7, which will round to 67, of course. And so on...
 
Back
Top