[ACS] FixedCubeRoot(x) to determine cube root

Post your example zscripts/ACS scripts/etc here.

[ACS] FixedCubeRoot(x) to determine cube root

Postby determin1st » Fri Nov 26, 2021 7:23 am

I was composing some bullet air resistance (drag force) formula and, the need of cube root calculation occured, so, here is a function i managed to construct:

Code: Select allExpand view
function int FixedCubeRoot(int x)
{
   // Halley's method formula:
   // y[next] = y*(y*y*y + 2*x)/(2*y*y*y + x)
   int e   = 0.0001, ee;
   int Yn  = x;
   int x2m = FixedMul(x, 2.0);
   int y, yy, yyy, yyy2m;
   int count = 0;
   do
   {
      y     = Yn;
      yy    = FixedMul(y, y);
      yyy   = FixedMul(yy, y);
      yyy2m = FixedMul(yyy, 2.0);
      Yn    = FixedDiv(yyy + x2m, yyy2m + x);
      Yn    = FixedMul(y, Yn);
      ee    = FixedDiv(Yn - y, y);
      count = count + 1;
      if (count > 1000)
      {
         Log(s:"FixedCubeRoot(",f:x,s:") failed! last approx=",f:Yn);
         break;
      }
      if (ee < 0) {
         ee = -ee;
      }
   }
   while (ee >= e);
   return Yn;
}

the precision is hardcoded - "e", not perfect but works
User avatar
determin1st
 
Joined: 06 Oct 2021

Return to Script Library

Who is online

Users browsing this forum: No registered users and 1 guest