Home:ALL Converter>How to increase precision of std::sin function on iOS

How to increase precision of std::sin function on iOS

Ask Time:2019-03-02T01:44:06         Author:Yellow

Json Formatter

I have a cross-platform application, which is an audio application and therefore uses sine waves a lot, and the std::sin() and other goniometric functions.

I noticed that particularly on the iOS platform, the precision of the std::sin() is extremely poor. I wrote the following test:

void TestSineZeroCrossings()
   const static float kTwoPi = 6.28318530718f;
   const static float epsilon = 1e-5f;

   for (int ii = 0; ii < 10000; ++ii)
       const float difference = std::abs(std::sin(kTwoPi * static_cast<float>(ii)));
       if (difference >  epsilon)
          printf("Zero crossing fail, difference: %f\n", difference);

On Windows and MaxOSX this passes (i.e. no print-outs), but on iOS this fails on pretty much every iteration. In fact, only with an epsilon > 0.004f does it succeed. That results in clearly audible noise in my application.

Is there a way to tell the compiler to use a better implementation that's not as lossy?

Author:Yellow,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/54949786/how-to-increase-precision-of-stdsin-function-on-ios
Sid S :

If you want more precision, use double or long double rather than float.\n\nFor instance,\n\nreplace\n\n const static float kTwoPi = 6.28318530718f;\n const static float epsilon = 10e-6f;\n\n\nwith\n\n const static double kTwoPi = 6.28318530718;\n const static double epsilon = 10e-6;\n\n\nand\n\nconst float difference = std::abs(std::sin(kTwoPi * static_cast<float>(ii)));\n\n\nwith\n\nconst double difference = std::abs(std::sin(kTwoPi * ii));\n",
chtz :

I would assume the implementation is quite accurate.\n\nYour actual problem is that kTwoPi * static_cast<float>(ii) gets rounded to the next float. E.g., for ii=10000 the value is (if I did not miscalculate): 62831.8515625\nIf you subtract 10000*2*pi in exact math from that you get approximately: -0.001509... And the sine of that value is approximately the same (and not 0). It is \"relatively\" close to zero but far away from your desired 10e-6 \"accuracy\".\n\nIf you want to have more accurate values for sin(x*pi), have a look at boost::math::sin_pi:\nhttps://www.boost.org/doc/libs/1_69_0/libs/math/doc/html/math_toolkit/powers/sin_pi.html",