Cinder icon indicating copy to clipboard operation
Cinder copied to clipboard

Add sqr function to CinderMath.h

Open IntellectualKitty opened this issue 4 years ago • 5 comments

IntellectualKitty avatar Jun 08 '20 15:06 IntellectualKitty

What's the use case for this?

paulhoux avatar Jun 25 '20 08:06 paulhoux

Using a squaring function makes for shorter, easier code. It also more closely resembles the mathematical equation the code is performing.

For example, this seems shorter, simpler, and easier to read:

float distance = cinder::math<float>::sqrt( cinder::math<float>::sqr( x2 - x1 ) + cinder::math<float>::sqr( y2 - y1 ) );

than this:

float deltaX = x2 - x1;
float deltaXSqr = deltaX  * deltaX;
float deltaY = y2 - y1;
float deltaYSqr = deltaY  * deltaY;
float distance = cinder::math<float>::sqrt( deltaXSqr + deltaYSqr );

IntellectualKitty avatar Jul 01 '20 21:07 IntellectualKitty

I am up for this change if there are no objections

andrewfb avatar Aug 29 '20 23:08 andrewfb

Just a minor point: what about calling it sq() or squared(), so there is no ambiguity about the sqr being "square root"? Or alternatively (better?), there is already a length2() in GLM (GLX) that does this -- squaring a scalar and doing dot(v,v) on vectors (which returns the squared length).

totalgee avatar Sep 01 '20 14:09 totalgee

As a side note:

float deltaX = x2 - x1;
float deltaXSqr = deltaX  * deltaX;
float deltaY = y2 - y1;
float deltaYSqr = deltaY  * deltaY;
float distance = cinder::math<float>::sqrt( deltaXSqr + deltaYSqr );

can be simplified to:

auto delta = vec2( x2 - x1, y2 - y1 );
auto distance = glm::length( delta );

or:

auto distanceSquared = glm::dot( delta, delta );

paulhoux avatar Oct 15 '20 22:10 paulhoux