You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When I execute my compiled file, everything runs, but at the very end when everything has successfully ran, I get a segmentation fault. This happens after closing a figure or when a figure has been saved as an image. Here is my cpp file (I spent some time troubleshooting to get the plotting to work which is why I have that comment before plotting :p) :
#include <iostream>
#include <cmath>
#include <vector>
#include <iomanip>
#include "matplotlibcpp.h"
namespace plt = matplotlibcpp;
// Assumption: Data points are equidistant (same h)
void print_vec(std::vector<double> n){
for (auto i : n){
std::cout << i << std::endl;
}
}
double forward_difference(std::vector<double> n, int i, double x_diff){
double f_prime{};
f_prime = (n[i + 1] - n[i]) / x_diff;
return f_prime;
}
double backward_difference(std::vector<double> n, int i, double x_diff){
double f_prime{};
f_prime = (n[i] - n[i - 1]) / x_diff;
return f_prime;
}
double central_difference(std::vector<double> n, int i, double x_diff){
double f_prime{};
f_prime = (n[i + 1] - n[i - 1]) / (2 * x_diff);
return f_prime;
}
int main (){
std::vector<double> x{};
double h{0.1};
// initialising x with data points
for (double i = 0; i <= 10; i += h){
x.push_back(i);
};
// display up to 3 decimal places
std::cout << std::fixed;
std::cout << std::setprecision(3);
// get values for f(x) = sin(x) and f'(x) = cos(x)
std::vector<double> sin_x{};
std::vector<double> cos_x{};
for (auto i : x){
sin_x.push_back(std::sin(i));
cos_x.push_back(std::cos(i));
}
// get the approximate derivative
std::vector<double> approx_deriv{};
for (int i = 0; i < x.size(); ++i){
if (i == 0){
approx_deriv.push_back(forward_difference(sin_x, i, h));
}
else if (i == x.size() - 1) {
approx_deriv.push_back(backward_difference(sin_x, i, h)) ;
}else {
approx_deriv.push_back(central_difference(sin_x, i, h));
}
}
// now it's time to plot the damn thing!
plt::named_plot("sin(x)", x, sin_x);
plt::named_plot("cos(x) (actual)", x, cos_x);
plt::named_plot("cos(x) (approx)", x, approx_deriv, "k--");
plt::legend();
plt::save("h_01.png");
//plt::show();
return 0;
}
When I execute my compiled file, everything runs, but at the very end when everything has successfully ran, I get a segmentation fault. This happens after closing a figure or when a figure has been saved as an image. Here is my cpp file (I spent some time troubleshooting to get the plotting to work which is why I have that comment before plotting :p) :
Here is my Makefile:
As mentioned before, the figures successfully display and show, its just the segmentation fault at the end. Is that something to be worried about?
The text was updated successfully, but these errors were encountered: