0

I want to print out a double number using my bisection method. I dont quite know how. I can return the double with up to 4 digits of accuracy after the decimal, but that's the default I take it. How do I print it out with much more accuracy. As much as I want to print at any time idealy.

void bisection(double start, double end, double tol, double (f)(double) ){

    double x = (end + start)/2;
    double num = f(x);
    if( std::abs(num) < tol) {
    //  return x;
    printf("Our approximation is: %20.10f", x);

    }

    if( num == 0){
        return x;
    }

    if( num < 0){
        std::cout << "f(x) is less than 0" << std::endl;
        std::cout << "f(x) = " << num << std::endl;
        start = x;
        bisection(start,end,tol, f );
    }
    else if(num > 0){
        std:: cout << "f(x) is greater than 0" << std::endl;
        std::cout << "f(x) = " << num << std::endl;
        end = x;
        bisection(start,end,tol, f );
    } 
}
Aldmeri
  • 187
  • 1
  • 2
  • 9

2 Answers2

1

Use std::setprecision(N), where N is the total number of digits to be printed.

double x = 1.23456789;
std::cout << "x: " << std::setprecision(3) << x << std::endl; // Prints 1.23
std::cout << "x: " << std::setprecision(7) << x << std::endl; // Prints 1.234567
CCicotta
  • 595
  • 4
  • 9
0

For C try the following

    # include <float.h>
     .  .  .
    printf("Our approximation is: %20.*lf", DBL_DIG , x);

Note: %lf is the correct specifier to double (not %f)

For C++ use setprecision(DBL_DIG) before output

VolAnd
  • 6,367
  • 3
  • 25
  • 43