Skip to content

Instantly share code, notes, and snippets.

@Experiment5X
Last active December 27, 2015 17:49
Show Gist options
  • Save Experiment5X/7364562 to your computer and use it in GitHub Desktop.
Save Experiment5X/7364562 to your computer and use it in GitHub Desktop.
This function will get the approximate length of a mathematical function if it were stretched into a straight line. This works by splitting the curve of the function up into a bunch of right triangles and then adding their hypotenuses together. The precision argument simply dictates the amount of triangles used. The more there are, the more accu…
#include <iostream>
#include <functional>
#include <algorithm>
using namespace std;
double GetFunctionLength(double start, double end, function<double(double)> mathFunc, int precision)
{
if (precision < 1)
return 0;
double xChange = end - start;
double sums = 0;
for (int i = 1; i <= precision; i++)
{
double legA = xChange / precision;
double legB = mathFunc(start + i * xChange / precision) - mathFunc(start + (i - 1) * xChange / precision);
// if the function has a slope of 0, then we just add it on
if (legB == 0)
sums += legA;
// otherwise, do pythagorean theorum to get the length of the side
else
sums += sqrt(legA * legA + legB * legB);
}
return sums;
}
int main()
{
auto f = [](double d) { return sin(d); };
cout << GetFunctionLength(0, 2 * 3.14159, f, 10000) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment