Skip to content

Instantly share code, notes, and snippets.

@dantsec
Created May 22, 2023 01:40
Show Gist options
  • Save dantsec/cc9761672df19dd78d8e145c309d7c15 to your computer and use it in GitHub Desktop.
Save dantsec/cc9761672df19dd78d8e145c309d7c15 to your computer and use it in GitHub Desktop.
Find any root with this algorithm!
#include <stdio.h>
#include <stdlib.h>
#define ROOT 1.21
#define POTENCY 2
#define PHASES 60
#define PRECISION 15
double* find_root(double *, double, int, int);
double potency_by(double, int);
int main(void) {
double range[] = {0.0, 0.0};
double* values = find_root(range, ROOT, POTENCY, PHASES);
printf("[%.*f ;; %.*f]\n", (int)PRECISION, (double)*(values + 0)\
, (int)PRECISION, (double)*(values + 1));
return 0;
}
double* find_root(double list_range[], double root, int potency, int phases) {
if(root <= 0.0 || root == 1.0)
return 0;
double x = 0.0;
double r = 0.0;
list_range[1] = root;
for(; phases >= 0; phases--) {
x = (list_range[0] + list_range[1]) / 2;
r = potency_by(x, potency);
if((r) > root)
list_range[1] = x;
else if((r) < root)
list_range[0] = x;
else {
printf("Root: %f\n", x);
exit(0);
}
}
return list_range;
}
double potency_by(double base, int potency) {
double result = 1.0;
for(; potency > 0; potency--)
result *= base;
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment