Strange result with multiplication

Back to topics list To post a new topic, please log in or register
avatar
316
ernest02 2015.03.05 09:06
 

I have a strange thing happening which I cannot figure out. If I run the following code

    for (i=1; i<=bars; i++) 
   {   
   closePrice = iClose(NULL,timeFrame,i);
   openPrice = iOpen(NULL,timeFrame,i);
   if (closePrice > openPrice)
   change = change + (closePrice - openPrice);
   else
   change = change + (openPrice - closePrice);
   if (CalcPoint == 0.01)
   change = NormalizeDouble(change,3);
   if (CalcPoint == 0.0001)
   change = NormalizeDouble(change,5);
}


I get a result for the variable "change" as follows:

0    09:51:31    2015.01.06 00:10  Scalper2 EURUSD,M1: Change is 0.00094

If I now multiply "change" with 100000

 for (i=1; i<=bars; i++) 
   {   
   closePrice = iClose(NULL,timeFrame,i);
   openPrice = iOpen(NULL,timeFrame,i);
   if (closePrice > openPrice)
   change = change + (closePrice - openPrice);
   else
   change = change + (openPrice - closePrice);
   if (CalcPoint == 0.01)
   change = NormalizeDouble(change,3) * 1000;
   if (CalcPoint == 0.0001)
   change = NormalizeDouble(change,5) * 100000;
}

I should get 94, but look what I get

0    10:00:23    2015.01.06 00:13  Scalper2 EURUSD,M1: Change is -9.223372036854776e+018

Can anyone tell me why this happens?


avatar
2017
gooly 2015.03.05 09:44 #
 

May be you should place the "* 100000" outside the loop?

for (i=1; i<=bars; i++) 
   {   
   closePrice = iClose(NULL,timeFrame,i);
   openPrice = iOpen(NULL,timeFrame,i);
   if (closePrice > openPrice)
   change = change + (closePrice - openPrice);
   else
   change = change + (openPrice - closePrice);
}
if (CalcPoint == 0.01)
   change = NormalizeDouble(change,3) * 1000;
if (CalcPoint == 0.0001)
   change = NormalizeDouble(change,5) * 100000;

avatar
316
ernest02 2015.03.05 09:50 #
 
Fantastic! Thanks a lot Gooly. Your advice solved the problem!
avatar
Moderator
3427
GumRai 2015.03.05 10:05 #
 

I know it is a small piece of code, but

   if (closePrice > openPrice)
   change = change + (closePrice - openPrice);
   else
   change = change + (openPrice - closePrice);

 Can be replaced with

   change += MathAbs(openPrice - closePrice);

 

avatar
316
ernest02 2015.03.05 10:14 #
 
Thanks Gumrai! That is far more efficient. I will use that approach in future - starting now with this code.
Back to topics list  

To add comments, please log in or register