I made a function in C++ that calculates the N-th Legendre polynomial and its derivative based on recursive formulas. It returns either zeros, bogus numbers or the "segmentation fault" error. I can't see what I did wrong. Care to help me out? Compiler is g++.
#include <iostream>#include <cmath>#include <iomanip>#include <vector>#include <functional>using namespace std;struct LegendreValues{ double function_value; double derivative_value;};LegendreValues calculateLegendrePolynomAndDerivative(const int&, const double&);double calculateLegendrePolynom(const int&, const double&);double calculateLegendreDerivative(const int&, const double&);int main(){ int N; LegendreValues values; cout << "Unesite red Legendreovog polinoma: " << endl; cin >> N; cout << calculateLegendrePolynom(N, 0.5) << "\n" << calculateLegendreDerivative(N, 0.5) << endl;}LegendreValues calculateLegendrePolynomAndDerivative(const int& N, const double& x){ LegendreValues results; if (N==0) { results.function_value = 1; results.derivative_value = 0; } else if (N==1) { results.function_value = x; results.derivative_value = 1; } else if (N>1) { results.function_value = (1/N) * ((2*N-1) * x * calculateLegendrePolynomAndDerivative(N-1, x).function_value - (N-1) * calculateLegendrePolynomAndDerivative(N-2, x).function_value); results.derivative_value = N/(1-x*x) * ( calculateLegendrePolynomAndDerivative(N-1, x).function_value - x * calculateLegendrePolynomAndDerivative(N, x).function_value); } return results;}
The recursive formulas used:Legendre recursions
As you can see, I tried splitting the two things apart, and it still doesn't work.