03-12-2014, 02:31 PM
(03-11-2014, 06:06 PM)Iceglade Wrote: If you're calculating square roots only, fractional exponentiation might not be what you're looking for. I would look into the Babylonian method first, which is represented by the recursive equation:
... where x is the number you're taking the square root of, and:
You can even have default to 1 if you really want, you will get to an accurate calculation in the end. The Babylonian method zones in on a correct square root very quickly ( will be much closer than ), so you can just calculate a few (10? play around with accuracy!) iterations of the Babylonian sequence and give that as a square root. You may also have to round at the end if you don't want or something, but that's all up to you.
Good luck!
Also, as a side note, if you insist on calculating arbitrary and you have exponential (and natural log), you can use the formula for an accurate exponent.
Another side note, just because I'm far too maths-happy for my own good, you could also have accuracy as an optional argument which would be a real feature that common sqrt functions don't have. So for instance, you could have something like
Just a thought.Code:public static double sqrt(int x, int accuracy) {
//calculations and stuff, in a loop based on accuracy
}
public static double sqrt(int x) {
return sqrt(x, //some default accuracy here)
}
Links:
http://en.wikipedia.org/wiki/Methods_of_...ian_method
http://stackoverflow.com/questions/94341...nentiation
http://en.wikipedia.org/wiki/Methods_of_...#Example_3 (This one is a last resort! Don't ruin it for yourself unless you're really stuck :3)
Accuracy, well I don't exactly want to use the accuracy method because that puts strain on a computer and it can't always be 100% accurate. I still like the N^0.50 method, but I can still make alternate method based on one of your suggestions.