20void plot_function(
long double x_min,
long double x_max,
long double y_min,
long double y_max,
21 int width,
int height,
long double label_interval)
23 std::vector<std::string> grid(height, std::string(width,
' '));
24 int x_axis = -1, y_axis = -1;
27 if (y_min <= 0 && y_max >= 0)
29 x_axis =
static_cast<int>(round((0 - y_min) / (y_max - y_min) * (height - 1)));
33 if (x_min <= 0 && x_max >= 0)
35 y_axis =
static_cast<int>(round((0 - x_min) / (x_max - x_min) * (width - 1)));
39 for (
int i = 0; i < width; ++i)
41 long double x = x_min + i * (x_max - x_min) / (width - 1);
43 if (y < y_min || y > y_max)
45 int j =
static_cast<int>(round((y - y_min) / (y_max - y_min) * (height - 1)));
46 if (j >= 0 && j < height)
48 grid[height - 1 - j][i] =
'*';
55 for (
int i = 0; i < width; ++i)
57 if (grid[x_axis][i] ==
' ')
58 grid[x_axis][i] =
'-';
65 for (
int i = 0; i < height; ++i)
67 if (grid[i][y_axis] ==
' ')
68 grid[i][y_axis] =
'|';
73 if (x_axis != -1 && y_axis != -1)
75 grid[x_axis][y_axis] =
'+';
79 std::cout <<
"\nFunction Plot:\n";
80 for (
const auto &row : grid)
82 std::cout << row <<
'\n';
86 std::string label_line(width,
' ');
87 for (
int label =
static_cast<int>(ceil(x_min / label_interval)) *
static_cast<int>(label_interval);
88 label <= static_cast<int>(floor(x_max / label_interval)) *
static_cast<int>(label_interval);
89 label +=
static_cast<int>(label_interval))
91 double relative_pos = (
static_cast<double>(label) - x_min) / (x_max - x_min);
92 int pos =
static_cast<int>(round(relative_pos * (width - 1)));
93 std::ostringstream oss_label;
94 oss_label << std::fixed << std::setprecision(0) << label;
95 std::string label_str = oss_label.str();
96 int start_pos = pos -
static_cast<int>(label_str.length() / 2);
99 if (start_pos +
static_cast<int>(label_str.length()) > width)
101 for (
size_t i = 0; i < label_str.length(); ++i)
103 label_line[start_pos + i] = label_str[i];
106 std::cout << label_line << std::endl;
107 std::cout <<
"x range: [" << x_min <<
", " << x_max <<
"]\n";
108 std::cout <<
"y range: [" << y_min <<
", " << y_max <<
"]\n\n";
void plot_function(long double x_min, long double x_max, long double y_min, long double y_max, int width, int height, long double label_interval)