0

I am currently Debugging a Software that I translated from C++ to C#. Everything goes fine until one values in C# is different from C++. the computation is :

v2z = vBlock.z * cos(phi) + v1x * sin(phi);

where

phi = 0.800, vBlock.z =-3.6127196945104552 and v1x= 4.5158996181380688

the result i C++ is

4.4408920985006262e-16

in C# the result is

0

And that is the Problem because in my condition later I need a value v2z >0.

After reading Topics on that subject I found These one interesting Formatting doubles for output in C#. I thought I could use the DoubleConverter.ToexactString() onto my C# values but that doesn't worked. Do you have any Ideas how to get exact the same values in C# as in C++?

Community
  • 1
  • 1
  • 2
    I've computed `-3.6127196945104552 * cos(0.800) + 4.5158996181380688 * sin(0.800)` and got `0.7225020468060972` – Dmitry Bychenko Aug 03 '16 at 09:15
  • As Dmitry has pointed out, both results you are getting (in C++ and C#) are incorrect. You will need to show an MCVE - in both languages - before people can help you. My guess is that your problem is with types of the variables (which causes either problems with precision or rounding). – Peter Aug 03 '16 at 09:26
  • Besides, the two values *are* the same - `4.4408920985006262e-16` is essentially zero. You *can't* compare floating point numbers for equality because rounding and scaling errors are guaranteed and may even depend on the evaluation order of the CPU operations. The **only** safe way to compare is to check whether the difference is below a certain small threshold. `1e-16` is far smaller than most people would use – Panagiotis Kanavos Aug 03 '16 at 09:29
  • Thank you all. Before I continue to code. What would you recommend? To say if the value in C++ is so small it should be zero? Then the original in C++ Simulation behave like the C# . That could be ok but not researched. –  Aug 03 '16 at 10:06
  • Both values are correct, the *double* type can store only 15 significant digits. The expression result is likely to be different because the C++ code generator uses SSE instructions and the 32-bit .NET jitter uses FPU instructions. The FPU calculates with *more* precision, using an internal 80-bit format for floating point values, SSE uses 64 bits. If your math model is not resilient to more accurate results then it is broken. Removing the jitter forcing so your .NET program runs in 64-bit mode and uses SSE instructions as well might be the quick fix you are looking for. – Hans Passant Aug 03 '16 at 10:38
  • Hans and Everybody thank you a lot for your answers, I have deactivated the jitter, it seems to work better but it is not exactly as wanted. Later in the code I make a condition : if (v2z>0) return 1; And this condition change everything because v2z is 4.44 e-16 in C++ and 0 in C# . The last one make then to many iteration I don't want. Is there no way to get the exact same value? –  Aug 04 '16 at 18:38

0 Answers0