Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created April 17, 2020 06:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/9ddf6bc7b211e76c3dc60324ec2975c2 to your computer and use it in GitHub Desktop.
Save parzibyte/9ddf6bc7b211e76c3dc60324ec2975c2 to your computer and use it in GitHub Desktop.
/*
____ _____ _ _ _
| _ \ | __ \ (_) | | |
| |_) |_ _ | |__) |_ _ _ __ _____| |__ _ _| |_ ___
| _ <| | | | | ___/ _` | '__|_ / | '_ \| | | | __/ _ \
| |_) | |_| | | | | (_| | | / /| | |_) | |_| | || __/
|____/ \__, | |_| \__,_|_| /___|_|_.__/ \__, |\__\___|
__/ | __/ |
|___/ |___/
Blog: https://parzibyte.me/blog
Ayuda: https://parzibyte.me/blog/contrataciones-ayuda/
Contacto: https://parzibyte.me/blog/contacto/
Copyright (c) 2020 Luis Cabrera Benito
Licenciado bajo la licencia MIT
El texto de arriba debe ser incluido en cualquier redistribución
===========================================
Método de la regla falsa
===========================================
*/
#include <cmath>
#include <iostream>
using namespace std;
double resolverEcuacion(double valor) {
// Con la ecuación: x^3-7x^2+14x-6
return pow(valor, 3) - 7 * pow(valor, 2) + 14 * valor - 6;
}
double obtenerxr(double a, double b, double fa, double fb) {
return ((a * fb) - (b * fa)) / (fb - fa);
}
int main() {
double a = 1;
double b = 3.2;
int iterador = 1;
double tolerancia = 0;
double anterior_xr = 0;
double toleranciaDeseada = 0.001;
printf("Método de la Regla Falsa\n");
printf("f(x)= x^3-7x^2+14x-6\n");
printf("Intervalos: [%0.2f, %0.2f]\n", a, b);
printf("Tolerancia: %0.4f\n\n\n", toleranciaDeseada);
printf("+-----------+-------------+-------------+-------------+-------------+"
"-------------+-------------+-------------+------------+\n");
printf("|Iteraciones| a | b | f(a) | f(b) "
"| xr | f(xr) | f(a)*f(xr) | Tolerancia |\n");
printf("+-----------+-------------+-------------+-------------+-------------+"
"-------------+-------------+-------------+------------+\n");
while (1) {
double fa = resolverEcuacion(a);
double fb = resolverEcuacion(b);
double xr = obtenerxr(a, b, fa, fb);
double fxr = resolverEcuacion(xr);
double fa_fxr = fa * fxr;
tolerancia = anterior_xr - xr;
if (iterador == 1) {
tolerancia = 0;
}
printf("|%10d |%12.8f |%12.8f |%12.8f |%12.8f |%12.8f |%12.8f |%12.8f "
"|%12.8f|\n",
iterador, a, b, fa, fb, xr, fxr, fa_fxr, tolerancia);
if (fxr > 0) {
a = xr;
} else {
b = xr;
}
anterior_xr = xr;
if (iterador != 1 && tolerancia < toleranciaDeseada) {
break;
}
iterador++;
}
printf("+-----------+-------------+-------------+-------------+-------------+"
"-------------+-------------+-------------+------------+\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment