I wrote this, it approaches 100% accuracy as you increase the number of iterations. 4 iterations are typically required to get an acceptable answer. it does it by calculating tangent lines and where they intersect the x axis (they get closer and closer to the number's root as you keep intersecting with the x axis). im just happy as a puffer fish that the goddam thing actually seems to work accurately with only 4 iterations.
EDIT: Mine is a lot slower than normal sqrt, but I'm glad that it at least works.Code:/* -Finds the root of x^2 - r -Need slope(m), need b, need curr x, need curry -FIXME: add tolerance variable? i.e answer must be within TOLERANCE from real root */ float IterSqrtf(float r, int numtries) { float m(0.0f); float b(0.0f); float currx=r; float curry(0.0f); float root(0.0f); //this is what gets returned while(numtries--) { curry = (currx*currx) - r; //y1 //Check to see if curry is < 0 m = 2 * currx; b = (-m*currx) + curry; root = -b / m; currx = root; } // trace << "tries: " << tries << "\n"; return root; }



LinkBack URL
About LinkBacks


