Home > Back-end >  Recursion Function over a Range of Inputs
Recursion Function over a Range of Inputs

Time:11-01

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)

  • x in between the range of -1<= x <= 1;

  • x in between the range of -1<= x <= 1;

  • x incrementing 0.1

Base conditions:

  • tolerance= 10^-6

    if (|x| < tolerance) return g(x)= x- x^3/6

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);
}

CodePudding user response:

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.

CodePudding user response:

Here is the corrected code for the errors above in the recursive float function.

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

    //Recursive Call
    float val= recFunc(x/2);
    return 2*val/1 val*val;
}
  • Related