Created
August 28, 2015 18:35
-
-
Save mortenpi/f20a93c8ed3ee7785e65 to your computer and use it in GitHub Desktop.
Function to create a vector of evenly spaced numbers in C++.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create a vector of evenly spaced numbers. | |
vector<double> range(double min, double max, size_t N) { | |
vector<double> range; | |
double delta = (max-min)/double(N-1); | |
for(int i=0; i<N; i++) { | |
range.push_back(min + i*delta); | |
} | |
return range; | |
} |
The performance difference is probably mainly due to initializing the vector to the correct size once and avoids the push_back() reallocation and copies when growing. Notice that the successive addition val += h
accumulates error. After just a few iterations, the result will drift from min + i * delta
from the original code.
Another version for 3D space (Unreal Engine API).
TArray<FVector> USplashComponent::distributeVectorsAcrossLine(FVector start, FVector end, int32 dens) const
{
TArray<FVector> vectors;
// safety check
if (dens <= 0)
{
return vectors;
}
else
{
dens = FMath::Clamp(dens, 0, 500);
FVector nextVector;
for (int32 i = 0; i < dens + 1; i++)
{
nextVector.X = FMath::Lerp(start.X, end.X, (float)i / (float)dens);
nextVector.Y = FMath::Lerp(start.Y, end.Y, (float)i / (float)dens);
nextVector.Z = FMath::Lerp(start.Z, end.Z, (float)i / (float)dens);
vectors.Add(nextVector);
}
return vectors;
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I agree @canberkgurel. The version provided assumes only the original three parameters are available, akin to
linspace
.