So I have a program that implements an adaptive 2D trapezoidal rule on the function x^2 + y^2 < 1, but it seems that the recursion isn't working -- the program here is a modified form of a (working) 1D trapezoidal method so I'm not sure where the code breaks down, it should return PI:
double trapezoidal(d_fp_d f,
double a, double b,
double c, double d) { //helper function
return 0.25*(b-a)*(d-c)*
(f(a, c)+f(a, d) +
f(b, c)+f(b, d));
}
double atrap( double a, double b, double c, double d, d_fp_d f, double tol )
{// helper function
return atrap1(a, b, c, d, f, tol );
}
double atrap1( double a, double b, double c, double d, d_fp_d f, double tol)
{
//implements 2D trap rule
static int level = 0;
const static int minLevel = 4;
const static int maxLevel = 30;
++level;
double m1 = (a + b)/2.0;
double m2 = (c + d)/2.0;
double coarse = trapezoidal(f,a,b,c,d);
double fine =
trapezoidal(f, a, m1, c, m2)
+ trapezoidal(f, a, m1, m2, d)
+ trapezoidal(f, m1, b, c, m2)
+ trapezoidal(f, m1, b, m2, d);
++fnEvals;
if( level< minLevel
|| ( abs( fine - coarse ) > 3.0*tol && level < maxLevel ) ){
fine = atrap1( a, m1, c, m2, f,tol/4.0)
+ atrap1( a, m1, m2, d, f, tol/4.0)
+ atrap1(m1, b, c, m2, f, tol/4.0)
+ atrap1(m1, b, m2, d, f,tol/4.0);
}
--level;
return fine;
}
where the function is given by
double ucircle( double x, double y)
{
return x*x + y*y < 1 ? 1.0 : 0.0;
}
and my main function is
int main()
{
double a, b, c, d;
cout << "Enter a: " <<endl;
cin >> a;
cout << "Enter b: " <<endl;
cin >> b;
cout << "Enter c: " <<endl;
cin >> c;
cout << "Enter d: " <<endl;
cin >> d;
cout << "The approximate integral is: " << atrap( a, b, c, d, ucircle, 1.0e-5) << endl;
return 0;
}
It will not actually run forever, but it actually run for a very long time that you think it is running for ever and that is the reason: in first run level is one and function enter your if and it call itself 4 times, now consider first time: it is also enter the if and call itself 4 more times and it continue ... for correctly chosen input like one specified by you, condition abs(fine - coarse) is always true so only thing that can stop the flow from entering the if is level that will be increased and then decreased so your function will be called almost 4^30 and that's really a big number that you can't see its end in an hour or 2!
Like BigBoss already wrote, your program should finish, it would just take a long time since 30 recursions mean 4^30 function calls for atrap1, which is 1152921504606846976. Just let that number sink in.
Here are some more things to consider:
You probably wanted to use fabs instead of abs in the "break condition". (I think you should get a warning for integer conversion - or something similar - for this) abs may return unpredictable values for float or double parameters. Very high values.
tol seems to be a variable that represents a target precision value. However, with each recursion you further increase this target precision. At the 10th recursion it's already about 1E-11. Not sure this is intended. Whatever tol means.
You probably don't want the /4.0 (the .0 is redundant by the way) in your recursive calls.
You do compile this with optimization, right?
trapezoidal, minLevel, maxLevel could be macros.
Your function does not like threaded execution due to level being static. You should make it a parameter for atrap1.
Related
/*I need to use the result from the (delta) function inside the (sol_ec_II) function for a school assignment.*/
#include <iostream>
#include <ctgmath>
using namespace std;
double delta(double a, double b, double c) {
return (b * b) - (4 * a * c);/* so I need to take this value [(b * b) - (4 * a * c)]
and use it in sol_ec_II in the places where I wrote "delta". */
}
void sol_ec_II(double a, double b, double c) {
if (delta < 0) {//here
cout << endl << "Polinomul NU are solutii.";
}
else {
double x1 = -1 * b - sqrt(delta);//here
double x2 = -1 * b + sqrt(delta);//here
}
}
// I would also need to use the (delta) function inside the (sol_ec_II) so they use the same
a, b, c values like this:
void sol_ec_II(double a, double b, double c) {
delta(a, b, c);
if (delta < 0) {
cout << endl << "Polinomul NU are solutii.";
}
else {
double x1 = -1 * b - sqrt(delta);
double x2 = -1 * b + sqrt(delta);
}
}
//so I don't understand how to get the value that results from delta(a, b, c) and use it inside the if statement and sqrt.
The result "comes out" of the function call at the time you call it. Look, you already know how sqrt works. sqrt is a function! You write sqrt(something) and that calls the function sqrt and it calls the function sqrt with the argument something and then the return value from sqrt gets used in the place where you wrote sqrt(something). e.g. 1 + sqrt(4) calculates 3.
Likewise the return value from delta gets used in the place where you wrote delta(a, b, c). If you want to call delta and then call sqrt (i.e. calculate the square root of the delta) you write sqrt(delta(a, b, c)).
Obviously, just calculating a number is pretty useless. You probably want to do something with the number, like saving it in a variable or printing it. Examples:
cout << "the square root of the delta is " << sqrt(delta(a,b,c)) << endl;
cout << "the delta plus one is " << (delta(a,b,c) + 1) << endl;
double the_delta = delta(a,b,c);
cout << "the delta is " << the_delta << " and the square root of the delta is " << sqrt(the_delta) << endl;
if (delta(a,b,c) < 0)
cout << "the delta is negative" << endl;
else
cout << "the delta isn't negative" << endl;
Note: Every time the computer runs delta(a,b,c) it calls the delta function. It doesn't remember the calculation from last time. You can see this because if you put cout instructions inside the delta function, they get printed every time the computer runs delta(a,b,c).
Of course I will not give you the solution for your program. I hope this helps you understand how functions work.
here you should pass parameters to deleta function in order to execute it:
void sol_ec_II(double a, double b, double c) {
if (delta(a,b,c) < 0) {//here
cout << endl << "Polinomul NU are solutii.";
}
else {
double x1 = -1 * b - sqrt(delta);//here
double x2 = -1 * b + sqrt(delta);//here
}
}
or you could save the result in a new variable called result for example, and after that use it, like that:
void sol_ec_II(double a, double b, double c) {
double result = delta(a,b,c);
if (result < 0) {//here
cout << endl << "Polinomul NU are solutii.";
}
else {
double x1 = -1 * b - sqrt(delta);//here
double x2 = -1 * b + sqrt(delta);//here
}
}
The Same thing for the second function, always to execute a function use parenthesis and pass between them the arguments that the function expects.
To reuse the value you get from calling a function multiple time use a variable:
double delta(double,double,double) { return 1.2; /*ignore this for now*/ }
void sol_ec_II(double a, double b, double c) {
const auto kDelta = delta(a, b, c);
if (kDelta < 0.0) {
// do stuff
} else {
const auto kRootD = sqrt(kDelta); // same idea
const auto x1 = -b - kRootD;
const auto x2 = -b + kRootD;
// use the variables
}
}
I use auto out of habit, you don't need to, double is fine.
Really new programmer with a really bad professor here.
I have this code that is supposed to get inputs from a text document (inputsFile) using a function (get_coefficients) and do stuff with it. Currently, everything works perfectly except it reads the same line from the file every time it's executed in the while loop in main. I've google around but I can't find anything that is implementable in my case. I've tried implementing while loops and trying to pass some sort of counting variable but nothing seems to work.
Since this is an assignment for school, I can't do anything fancy. So the more elementary the explanation, the better please, haha. Thank you in advance for any help I get.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//=======================================FUNCTIONS======================================
//a function that displays instructions
void display_instructions() {
cout << "Enter a, b, c: ";
}
//a function that gathers inputs
void get_coefficients(double& a, double& b, double& c) {
ifstream inputsFile;
string inputs;
string inputString;
inputsFile.open("textinputs.txt");
inputsFile >> a >> b >> c;
cout << a << b << c;
inputsFile.close();
}
//a function that calculates a discriminant
double calc_discriminant(double a, double b, double c) {
double discriminant = (b * b) - (4 * a * c);
return discriminant;
}
//a function that calculates root 1
double calc_root_1(double a, double b, double c, double disc) {
double r1 = ((-b) + (sqrt(disc))) / (2 * a);
return r1;
}
//a function that calculates root 2
double calc_root_2(double a, double b, double c, double disc) {
double r2 = ((-b) - (sqrt(disc))) / (2.0 * a);
return r2;
}
void display(double r1, double r2) {
cout << "the roots are " << r1 << " and " << r2 << "." << endl;
}
//=======================================EXCECUTE=======================================
int main()
{
//while again is true
for (int i = 0; i < 3; i++) {
double a, b, c;
display_instructions();
//run get numbers
get_coefficients(a, b, c);
//if discrimant less than 0 stop the program
if (calc_discriminant(a, b, c) < 0) {
cout << "No real solution" << endl;
}
else { //else get the roots
double disc = calc_discriminant(a, b, c);
double r1 = calc_root_1(a, b, c, disc);
double r2 = calc_root_2(a, b, c, disc);
//print the roots
display(r1, r2);
}
}
}
The problem here is that when you do inputsFile.open() you're opening the file from the start. You should only open the file once so each time you read from it you'll read the next line from where you were the last time. However, the ifstream will be deleted at the end of the scope if you don't save it anywhere. What you can do is initialize the ifstream in main() and then pass it to the function by reference so the ifstream will still be there until the program reaches the end of main.
I think this should work for what you want:
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
using namespace std;
//=======================================FUNCTIONS======================================
//a function that displays instructions
void display_instructions() {
cout << "Enter a, b, c: ";
}
//a function that gathers inputs
void get_coefficients(double& a, double& b, double& c, ifstream& inputsFile) {
string inputs;
string inputString;
inputsFile >> a >> b >> c;
cout << a << b << c;
}
//a function that calculates a discriminant
double calc_discriminant(double a, double b, double c) {
double discriminant = (b * b) - (4 * a * c);
return discriminant;
}
//a function that calculates root 1
double calc_root_1(double a, double b, double c, double disc) {
double r1 = ((-b) + (sqrt(disc))) / (2 * a);
return r1;
}
//a function that calculates root 2
double calc_root_2(double a, double b, double c, double disc) {
double r2 = ((-b) - (sqrt(disc))) / (2.0 * a);
return r2;
}
void display(double r1, double r2) {
cout << "the roots are " << r1 << " and " << r2 << "." << endl;
}
//=======================================EXCECUTE=======================================
int main()
{
ifstream inputsFile;
inputsFile.open("textinputs.txt");
//while again is true
for (int i = 0; i < 3; i++) {
double a, b, c;
display_instructions();
//run get numbers
get_coefficients(a, b, c, inputsFile);
//if discrimant less than 0 stop the program
if (calc_discriminant(a, b, c) < 0) {
cout << "No real solution" << endl;
}
else { //else get the roots
double disc = calc_discriminant(a, b, c);
double r1 = calc_root_1(a, b, c, disc);
double r2 = calc_root_2(a, b, c, disc);
//print the roots
display(r1, r2);
}
}
inputsFile.close();
}
i need to gain a better understanding of function definition, declarations and proper calls using this program. I really need the understanding of how to use them. Could you show me the proper way to write this program with all three correct and explained?
#include <stdio.h>
#include <math.h>
quad_equation(float a, float b, float c);
int main()
{
float a, b, c, determinant, r1,r2;
printf("Enter coefficients a, b and c: ");
scanf("%f%f%f",&a,&b,&c);
determinant=b*b-4*a*c;
if (determinant>0)
{
r1= (-b+sqrt(determinant))/(2*a);
r2= (-b-sqrt(determinant))/(2*a);
printf("Roots are: %.2f and %.2f",r1 , r2);
}
else if (determinant==0) { r1 = r2 = -b/(2*a);
printf("Roots are: %.2f and %.2f", r1, r2);
}
else (determinant<0);
{
printf("Both roots are complex");
}
return 0;
I just solved this exact question here : (I guess this is a part of an assignment )
https://stackoverflow.com/a/19826495/1253932
Also looking at your code .. you never use the function quad equation .. also you haven't defined the type of the function ( int/void/float/char) etc.
For ease: ( here is the entire code ) -- ask me if you don't understand anything
#include <stdio.h>
#include <math.h>
// function declarations
void twoRoots (float a,float b,float delta);
void oneRoot (float a,float b,float delta);
int main (void)
{
//Local Declarations
float a;
float b;
float c;
float delta;
// float solution;
printf("Input coefficient a.\n");
scanf("%f", &a);
printf("Input coefficient b.\n");
scanf("%f", &b);
printf("Input coefficient c.\n");
scanf("%f", &c);
printf("%0.2fx^2 + %0.2fx + %0.2f\n", a, b, c);
delta = (float)(b*b) - (float)(4.0 * a * c);
printf("delta = %0.2f\n",delta);
if (delta > 0){
twoRoots(a,b,delta);
}else if (delta == 0) {
oneRoot(a,b,delta);
}else if (delta < 0.0){
printf("There are no real roots\n");
}
return 0;
}
void twoRoots (float a,float b,float delta)
{
float xOne;
float xTwo;
float deltaRoot;
printf("There are two distinct roots.\n");
deltaRoot = sqrt(delta);
xOne = (-b + deltaRoot) / (2*a);
xTwo = (-b - deltaRoot) / (2*a);
printf("%.2f", xOne);
printf("%.2f", xTwo);
}
void oneRoot(float a,float b,float delta)
{
float xOne;
// float xTwo;
// float deltaRoot;
printf("There is exactly one distinct root\n");
xOne = -b / (2*a);
printf("%.2f", xOne);
}
EDIT:
A slightly more optimized and better functioning code that I made from the above mentioned code:
http://pastebin.com/GS65PvH6
Edit2:
From your comments you try to do this:
printf("Enter coefficients a, b and c: ");
scanf("%f%f%f",&a,&b,&c);
This will fail if you input something like this: 121
Beacuse scanf will read the whole 121 into a and it will have nothing for b,c ( rather it will put \n(enter) into b and undefined into c )
So use the scanf the way I have used it in my code
OK - this is full of problems! I attempt to point them out, and show what "better" looks like. I hope this helps.
quad_equation(float a, float b, float c);
This is probably intended to be a "function prototype". A prototype tells the compiler "I am going to use this function later, and this is how it needs to be called, and the type it returns". You did not specify a return type; probably you want to use int to say whether you found roots or not, and print out the result in the function. Better would be to pass space for two return values as a parameter:
int quad_equation(float a, float b, float c, float* x1, float* x2);
Now we can use the main program to get input/output, and let the function solve the problem:
int main(void) {
{
float a, b, c, r1, r2;
int n;
// here you get the inputs; that seems OK
printf("Enter coefficients a, b and c: ");
scanf("%f %f %f",&a,&b,&c);
// now you have to "call your function"
// note that I make sure to follow the prototype: I assign the return value to an int
// and I pass five parameters: the coefficients a, b, c and the address of two variables
// x1 and x2. These addresses will be where the function puts the roots
n = quad_equation(a, b, c, &r1, &r2);
// when the function returns, I can print the results:
printf("There are %d roots:\n", n);
// based on the value of n, I change what I want to print out:
if (n == 2) printf(" %f and ", r1); // when there are two roots I print "root 1 and"
if (n > 0) printf("%f\n", r2); // when there is at least one root, I print it
// note that if n == 0, I would skip both print statements
// and all you would have gotten was "There are 0 roots" in the output
}
int quad_equation(float a, float b, float c, float* x1, float* x2) {
// function that computes roots of quadratic equation
// and returns result in x1 and x2
// it returns the number of roots as the return value of the function
float determinant;
determinant=b*b-4*a*c;
if (determinant>0)
{
*x1 = (-b+sqrt(determinant))/(2*a);
*x2= (-b-sqrt(determinant))/(2*a);
return 2;
}
if (determinant==0) {
*x1 = *x2 = -b/(2*a);
return 1;
}
return 0;
}
I'm having issues with my adaptive trapezoidal rule algorithm in C++ -- basically, regardless of the tolerance specified, I get the same exact approximation. The recursion is supposed to stop very early for large tolerances (since abs(coarse-fine) is going to be smaller than 3.0*large tolerance and minLevel of recursion is about 5).
However, what this function does is run the maximum number of times regardless of choice of tolerance. Where did I mess up?
EDIT: Perhaps there are issues in my helper functions?
double trap_rule(double a, double b, double (*f)(double),double tolerance, int count)
{
double coarse = coarse_helper(a,b, f); //getting the coarse and fine approximations from the helper functions
double fine = fine_helper(a,b,f);
if ((abs(coarse - fine) <= 3.0*tolerance) && (count >= minLevel))
//return fine if |c-f| <3*tol, (fine is "good") and if count above
//required minimum level
{
return fine;
}
else if (count >= maxLevel)
//maxLevel is the maximum number of recursion we can go through
{
return fine;
}
else
{
//if none of these conditions are satisfied, split [a,b] into [a,c] and [c,b] performing trap_rule
//on these intervals -- using recursion to adaptively approach a tolerable |coarse-fine| level
//here, (a+b)/2 = c
++count;
return (trap_rule(a, (a+b)/2.0, f, tolerance/2.0, count) + trap_rule((a+b)/2.0, b, f, tolerance/2.0, count));
}
}
EDIT: Helper and test functions:
//test function
double function_1(double a)
{
return pow(a,2);
}
//"true" integral for comparison and tolerances
//helper functions
double coarse_helper(double a, double b, double (*f)(double))
{
return 0.5*(b - a)*(f(a) + f(b)); //by definition of coarse approx
}
double fine_helper(double a, double b, double (*f)(double))
{
double c = (a+b)/2.0;
return 0.25*(b - a)*(f(a) + 2*f(c) + f(b)); //by definition of fine approx
}
double helper(double a, double b, double (*f)(double x), double tol)
{
return trap_rule(a, b, f, tol, 1);
}
And here's what's in main():
std::cout << "First we approximate the integral of f(x) = x^2 on [0,2]" << std::endl;
std::cout << "Enter a: ";
std::cin >> a;
std::cout << "Enter b: ";
std::cin >> b;
true_value1 = analytic_first(a,b);
for (int i = 0; i<=8; i++)
{
result1 [i] = helper(a, b, function_1, tolerance[i]);
error1 [i] = fabs(true_value1 - result1 [i]);
}
std::cout << "(Approximate integral of x^2, tolerance, error )" << std::endl;
for (int i = 0; i<=8; i++)
{
std::cout << "(" << result1 [i] << "," << tolerance[i] << "," << error1[i] << ")" << std::endl;
}
I find that exactly the opposite of what you suggest is happening --- the algorithm is terminating after only minLevel steps --- and the reason is due to your usage of abs, rather than fabs in the tolerance test. The abs is converting its argument to an int and thus any error less than 1 is getting rounded to zero.
With the abs in place I get this output from a very similar program:
(0.333496,0.001,0.00016276)
(0.333496,0.0001,0.00016276)
(0.333496,1e-05,0.00016276)
(0.333496,1e-06,0.00016276)
(0.333496,1e-07,0.00016276)
(0.333496,1e-08,0.00016276)
(0.333496,1e-09,0.00016276)
(0.333496,1e-10,0.00016276)
(0.333496,1e-11,0.00016276)
Replacing with fabs I get this:
(0.333496,0.001,0.00016276)
(0.333374,0.0001,4.06901e-05)
(0.333336,1e-05,2.54313e-06)
(0.333334,1e-06,6.35783e-07)
(0.333333,1e-07,3.97364e-08)
(0.333333,1e-08,9.93411e-09)
(0.333333,1e-09,6.20882e-10)
(0.333333,1e-10,3.88051e-11)
(0.333333,1e-11,9.7013e-12)
My code works when the values are small e.g. [a = 1, gos = 0.5, N = 1] & [a = 1, gos = 0.2 , N = 2].
However, it crashes when bigger values are entered. e.g.[a = 10, gos = 0.01, N = 18] & [a=50, gos=0.01, N=64].
How can I fix it?
Here's the code:
#include <cstdlib>
#include <iostream>
using namespace std;
double num_trunks(double A, double B, int N);
double num_trunk_checker(double B, double gos, int N, double A);
double num_trunks(double A, double B, int N)
{
double gos_prev = 1;
double gos;
int k = 1;
while (k != (N+1))
{
gos = (A*gos_prev)/(k+(gos_prev)*A);
gos_prev = gos;
k++;
};
num_trunk_checker(B,gos,N,A);
}
double num_trunk_checker(double B, double gos, int N, double A)
{
if (B != gos)
{
N = N + 1;
num_trunks(A,B,N);
}
else
{
cout << "Number of trunks: " << N << "\n";
}
}
int main(int argc, char *argv[])
{
double A, gos;
int N = 1;
cout << "A: ";
cin >> A;
cout << "gos: ";
cin >> gos;
num_trunks(A,gos,N);
system("PAUSE");
return EXIT_SUCCESS;
}
In num_trunks(A, B, N), you calculate a gos value, and then call num_trunk_checker(B, gos, N, A). But in num_trunk_checker, if B does not match gos, you turn around and call num_trunks(A, B, N+1). So the only thing that changed is a larger N, and you get infinite recursion if gos never equals B.
num_trunks(A, B, N)
calculuate gos (which has to be less than 1)
num_trunk_checker(B, gos, N, A)
num_trunk_checker(B, gos, N, A)
if (B != gos) num_trunks(A, B, N+1)
It is possible for gos to step over the value of B, so you never get equality.
Perhaps what you meant was:
if (gos > B) //...
you should read the FAQ about floating point comparisons
http://www.parashift.com/c++-faq/floating-point-arith.html
then try sth like
if (fabs(B-gos)<1.e-6)
in num_trunk_checker function
Without more information (what crashes? How long does it take?) it is impossible to solve your problem perfectly. But some reasonable guesses can be made.
Floating point comparisons are not completely accurate and are usually done by subtracting the two values and comparing against a small value (called epsilon). It might be better, when checking (B != gos), to do something like (B - gos < .00001). Without this, the computation may not terminate; and if it did not, the recursion would continue indefinitely, until the stack overflowed and the program crashed.
Another possibility (I am not running the program to see what happens myself) is that with larger values, the multiplication causes them to overflow (to exceed the maximum possible value that can be represented in a double), causing an exception to be thrown.