7

I have this code:

#include <iostream>
#include <cmath>
#include <stdlib.h>
using namespace std;
double f(double x);
double biseccion(double a, double b, double tolerancia, int maxiter);
int main()
{
    double a, b, raiz;
    double tolerancia=0.00000;
    int maxiter=25;
    cout << "Input begin of interval: ";
    cin >> a;
    cout << "Input end of interval: ";
    cin >> b;
    cout << "\n";
    cout << "  # de"<<"\n"<<"Iteration"<<"\t"<<"   A"<<"\t"<<"   B"<<"\t"<<"   C"<<"\t"<<"   f(c)"<<endl;
    raiz=biseccion(a,b,tolerancia,maxiter);
    cout << "\n";
    cout << "The root is: "<< raiz <<endl;
    return 0;
}

 double f(double x)
 {
        return x*x*x-x-2;
 }
 double biseccion(double a, double b, double tolerancia, int maxiter)
 {
        double c;
        int numiter=1;
        do
        {
            c=(a+b)/2;
            if(f(a)*f(c)<0)
            {
               b=c;
            }
            else
            {
               a=c;
            }
            cout<<"     "<<numiter<<"\t"<<"\t"<<a<<"\t"<<b<<"\t"<<c<<"\t"<<f(c)<<endl;
            numiter++;
         }
         while((abs(f(c))>tolerancia)&&(numiter<maxiter));
         return c;
}

Instead of writing "x*x*x-x-2" in my code, I want user to input it before asking for begin of interval. How can I do that?

I try using a variable to store the "x*x*x-x-2", but none work.

Ashir
  • 511
  • 2
  • 8
  • 23
  • 1
    You'll want a library for expression evaluation, such as muParser. – Vaughn Cato Mar 20 '13 at 14:18
  • Having a user define a function is not so simple, especially in a compiled language. – Waleed Khan Mar 20 '13 at 14:19
  • possible dup http://stackoverflow.com/questions/9503455/equation-parsing-library-c – Shafik Yaghmour Mar 20 '13 at 14:20
  • If it is only polynomial bisection just ask for the coefficients of every exponent and than do your calculation based on these inputs. In your example the coefficients would be -2; -1; 0; 1. http://upload.wikimedia.org/math/f/2/7/f27a2ba683c642c5c52edf45476d4709.png –  Mar 20 '13 at 14:22
  • Is there a way to just replace the equation after the return with what the user entered? – Ashir Mar 26 '13 at 05:46

1 Answers1

7

You need to parse the input, its probably not as easy as you are thinking but there are some libraries that can help you.

muparser.sourceforge.net/

code.google.com/p/expressionparser/

partow.net/programming/exprtk/index.html

here is also a solution in c# that might help you too.

Is there a string math evaluator in .NET?

Community
  • 1
  • 1
Luis Tellez
  • 2,622
  • 1
  • 17
  • 28