Why the same function in the loop gives different output?

Hi, I'm using a signal generator produce two sinusoidal signals with the same frequency 500 Hz, the same amplitude and the same offset. The only thing different is the phase angle. There are 60 degree phase difference between the two signal.

I connect the outputs of the 2 signals to Pin A0 and A1 in the arduino DUE. I'm going to collect both signals every 200 microseconds and the time increments. And then I use a mathematic method, which I'm sure is correct, to calculate the cosine(phase difference) according to the arrays I collect. The collection period (line 51-87) and the calculation period(line 99) is both in the loop{}.

What I don't understand is the phase difference is fixed , 60 degree. Each time when running the loop, the calculation method is the same. All variables needs accumulation is reset to 0 at the start of the calculation. But the results cos(phase difference) keeps change when I run the program. The result should keeps around 0.5(cos(pi/3)). But what I can get is an outcome ranges between 0.29 to 0.48.

I think the only thing updated in the loop are the arrays B2[500], B3[500] and dt[499] recorded each time. But that still can't explain why the output varies in such a wide range. I hope the output can keep constant and have an accurate result.

Does anyone meet the same problem before? Do you have any advice for this case?

cosphiwithresolution.ino (4.62 KB)

Post your code in code tags. </>

To calculate phase difference between two sinusoidal signals based on zero-crossing points and in the form of power factor cos theta, this link may be helpful for you.