c++for-looprecursioncmath

Recursion Function over a Range of Inputs


A newbie learning C++ here. Im currently practicing the concept of calling a recursive function between a range of inputs by utilizing a for loop and am running into a "segmentation fault : 11" error.

The attempted code and the error Im facing is posted below. Now I know this error is most likely is a result of me not being comfortable with the concept of recursion so any insight would help greatly! (Note: This is not for homework, just a challenge problem I would like to understand better.)

Here is the math function i am trying to apply recursion to along with its base case and its range of inputs to test.

g(2x)= 2g(x)/ 1+g^2(x)

Base conditions:

enter image description here

Attempted Code

//Libraries
#include <iostream> 
#include <cmath>
using namespace std;

//Function Prototypes
float recFunc(float);

int main(int argc, char** argv) {
    //Call Recursive Function and Output Results

    //from negative 1 to z
    for (float x=-1.0; x<=0; x+=0.1f){
        cout<<"X Value = "<<x<<" : g(2x) = "<<recFunc(x)<<endl;
    }

    //from 0 to 1
    for (float x=0; x<1.1; x+=0.1f){
        cout<<"X Value = "<<x<<" : g(2x) = "<<recFunc(x)<<endl;
    }
    return 0;
}

float recFunc(float x){
    //Base condition
    float tol= 1e-6f;
    if(abs(x)< tol) return x-x*x*x/6;

    //Recursive Call
    float val= 2*(x-x*x*x/6)/1+(x-x*x*x/6)*(x-x*x*x/6);
    return 2*recFunc(val);
}

Solution

  • The posted math formula is basically

    g(2 * x) = F(g(x))

    It can be rewritten as

    g(x) = F(g( x / 2 ))

    So, to fix recFunc, you have to:

    1. Evaluate g at x/2. This is the recursive call to recFunc, but with x / 2 as argument. Assign the returned value to variable, like val.

    2. Return F(val). Meaning, apply the posted formula to value calculated in the previous point.