Created
May 7, 2019 23:10
-
-
Save GuilhermeRossato/13a072c757ead85c2325177a29c4534d to your computer and use it in GitHub Desktop.
Incomplete source for a program that computes a root of a polynomial of any size with a guessing-based approach
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Incomplete source for a program that computes a root of a polynomial of any size with a guessing-based approach | |
| // | |
| // File: approximate-root | |
| // Compilation: gcc -o main approximate-root.c | |
| // Run: ./main | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| double get_value_of_n_degree_polynomial(double x, double *coeficients, int coeficients_length) { | |
| if (coeficients_length <= 0) { | |
| return 0; | |
| } | |
| if (coeficients_length == 1) { | |
| return coeficients[0]; | |
| } | |
| return x*get_value_of_n_degree_polynomial(x, coeficients, coeficients_length-1)+coeficients[coeficients_length-1]; | |
| } | |
| int find_root_n_degree_polynomial(double *coeficients, int coeficients_length, double starting_value, double * x_out) { | |
| double x, last_x, step, target, value, error, next_value, next_error; | |
| int limit = 100; | |
| step = starting_value/4; | |
| last_x = x - step; | |
| do { | |
| x = starting_value; | |
| target = 0; | |
| value = get_value_of_n_degree_polynomial(last_x, coeficients, coeficients_length); | |
| error = target - value; | |
| next_value = get_value_of_n_degree_polynomial(x, coeficients, coeficients_length); | |
| next_error = target - next_value; | |
| if (next_error > error) { | |
| step = - step / 2; | |
| } else if (next_error < error) { | |
| step = step * 0.95; | |
| } | |
| x = x + step; | |
| } while (limit-- > 0) | |
| } | |
| int main() | |
| { | |
| double c[16], x; | |
| x = 0; | |
| c[0] = 1; | |
| c[1] = 7; | |
| c[2] = 0.5; | |
| double result; | |
| result = x*(x*(c[0])+c[1])+c[2]; | |
| printf("Value should be %.3f!\n", result); | |
| result = get_value_of_n_degree_polynomial(x, c, 3); | |
| printf("Value is %.3f!\n", result); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment