Replace sqrt in Dimension by Fast inverse square root
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
parent
d6eb9ea364
commit
497d2173e8
2 changed files with 24 additions and 2 deletions
|
@ -1,5 +1,6 @@
|
|||
import * as React from 'react';
|
||||
import { NOTCHES_LENGTH } from '../../../utils/default';
|
||||
import { Qrsqrt } from '../../../utils/math';
|
||||
|
||||
interface IDimensionProps {
|
||||
id: string
|
||||
|
@ -32,8 +33,8 @@ export const Dimension: React.FC<IDimensionProps> = (props: IDimensionProps) =>
|
|||
const [deltaX, deltaY] = [(props.xEnd - props.xStart), (props.yEnd - props.yStart)];
|
||||
|
||||
// Get the unit vector
|
||||
const norm = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
|
||||
const [unitX, unitY] = [deltaX / norm, deltaY / norm];
|
||||
const inv = Qrsqrt(deltaX * deltaX + deltaY * deltaY);
|
||||
const [unitX, unitY] = [deltaX * inv, deltaY * inv];
|
||||
|
||||
// Get the perpandicular vector
|
||||
const [perpVecX, perpVecY] = [unitY, -unitX];
|
||||
|
|
21
src/utils/math.ts
Normal file
21
src/utils/math.ts
Normal file
|
@ -0,0 +1,21 @@
|
|||
const bytes = new ArrayBuffer(Float32Array.BYTES_PER_ELEMENT);
|
||||
const floatView = new Float32Array(bytes);
|
||||
const intView = new Uint32Array(bytes);
|
||||
const threehalfs = 1.5;
|
||||
|
||||
/**
|
||||
* Fast inverse square root
|
||||
* http://en.wikipedia.org/wiki/Fast_inverse_square_root
|
||||
* https://youtu.be/p8u_k2LIZyo
|
||||
* @param number Number to square root
|
||||
* @returns Approximation of the squqre root of the number
|
||||
*/
|
||||
export function Qrsqrt(number: number): number {
|
||||
const x2 = number * 0.5;
|
||||
floatView[0] = number;
|
||||
intView[0] = 0x5f3759df - (intView[0] >> 1);
|
||||
let y = floatView[0];
|
||||
y = y * (threehalfs - (x2 * y * y));
|
||||
|
||||
return y;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue