I'm having trouble calculating the Nth root of a given value. I don't understand what's going wrong in the algorithm, but the values are incredibly close. Only off by about 0.78891 for small values, and about 0.52 for larger ones. So any help with this is appreciated; I don't want to use Math.Pow for this.

``````public static float NthRoot(int Root, int Value) {
if (Value == 0) { return 0; }

double Δ = (Value / Root) + 1;
double Ω = (Δ + (Value / Root)) / Root;

while (Ω < Δ) {
Δ = Ω;
Ω = (Δ + (Value / Δ)) / Root;
}

return (float)Δ;
}``````

Thanks

Because floating point numbers aren't exact (in most cases) you need an error margin, usually called 'epsilon', to let you know when you are done. I'm not sure what formula you are using there, but here's one that works (Note: It requires a power function, otherwise how can you test if you are close to the answer?)

``````static float epsilon = 0.00001f;

static float NthRoot(float A, int N) {
float n = N;
float x = A / n;
while (Math.Abs(A-Power(x,N)) > epsilon) {
x = (1.0f/n) * ((n-1)*x + (A/(Power(x, N-1))));
}

return x;
}

static float Power(float a, int n) {
float result = 1.0f;
for (int i = 0; i < n; i++) {
result *= a;
}

return result;
}``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.