Skip to content

Instantly share code, notes, and snippets.

@DoCTheBest01
Created December 10, 2023 22:07
Show Gist options
  • Save DoCTheBest01/8697fa8284847c8f24821e7bacccc86e to your computer and use it in GitHub Desktop.
Save DoCTheBest01/8697fa8284847c8f24821e7bacccc86e to your computer and use it in GitHub Desktop.
CSharp Nth Root Function
public static Type Root<Type>(dynamic number, int root) where Type : struct
{
const double epsilon = 1e-10; // Tolerance level for convergence
Type guess = (Type)Convert.ChangeType(number / root, typeof(Type)); // Initial guess
while (Absolute<Type>(Power<Type>(guess, root) - number) > epsilon)
{
guess = (Type)Convert.ChangeType(((dynamic)(root - 1) * (dynamic)guess + (dynamic)number / Power<Type>((dynamic)guess, root - 1)) / root, typeof(Type));
}
return guess;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment