SHARE
TWEET

Math Func

a guest Mar 10th, 2014 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.treehouseelite.elib.math;
  2.  
  3. import java.util.Random;
  4.  
  5. import com.badlogic.gdx.math.Vector2;
  6. import com.badlogic.gdx.math.Vector3;
  7.  
  8. /**
  9.  * An alternative to the java.lang.Math class, uses several bit-wise
  10.  * calculations to conduct mathematical calculations efficiently. <br />
  11.  * Mostly solves Java SE's odd inefficiency when it comes to Trigonometric
  12.  * functions (sine and cosine only at this time, tangent may be added).<br />
  13.  * <br />
  14.  * Also provides possibly more efficient ceil, floor and round methods as well
  15.  * as Pi, Pau, Tau and e in relatively precise float values.<br />
  16.  * <br />
  17.  * More Recently functions for square roots, power of two roots, any logarithm
  18.  * (using Math.log for Change of base), power and so on have been created using
  19.  * pretty efficient methods of calculation albeit relying on recursion for
  20.  * simplification.<br />
  21.  * <br />
  22.  * Only Dependency Outside of LibGDX is java.util.Random
  23.  *
  24.  * @author Matthew Crocco
  25.  *
  26.  */
  27. public final class Maths {
  28.  
  29.         // Prevent Instantiation
  30.         private Maths() {
  31.         }
  32.  
  33.         /**
  34.          * Eulers Number, used in natural exponents and natural logs for natural
  35.          * growth, natural decay, compound interest and so on. Its all natural.
  36.          */
  37.         public static final float E = 2.71828182F;
  38.  
  39.         /**
  40.          * Defined as Two Times the Ratio of a Circles Circumference to its
  41.          * Diameter.<br />
  42.          * Its main function is in trigonometric functions or physics where it
  43.          * represents a complete unit circle, following a logical reasoning. <br/>
  44.          * It represents 2pi so 2piD turns into tauD and formulae for the Period of
  45.          * a Spring or Pendulum repalce 2pi with tau... yes I am pushing an
  46.          * agenda...
  47.          */
  48.         public static final float TAU = 6.283185302F;
  49.  
  50.         /**
  51.          * A rational compromise in the Pi vs Tau debate by Randall Munroe at <a
  52.          * href="http://xkcd.com/1292/">XKCD</a><br />
  53.          * Also its an awesome sounding word... and why not include it? 1.5*pi
  54.          */
  55.         public static final float PAU = 4.71238898F;
  56.  
  57.         /** The ratio of a circles circumference to its diameter */
  58.         public static final float PI = 3.14159265F;
  59.  
  60.         private static final float degreesToRadians = TAU / 360;
  61.         private static final float degRad = degreesToRadians;
  62.         private static final float radDeg = 180 / PI;
  63.  
  64.         private static final int SIN_BITS = 14;
  65.         private static final int SIN_MASK = ~(-1 << SIN_BITS);
  66.         private static final int SIN_COUNT = SIN_MASK + 1;
  67.         private static final float degIndex = SIN_COUNT / 360;
  68.         private static final float radIndex = SIN_COUNT / TAU;
  69.  
  70.         private static final float F_UPPER = 2048f;
  71.         private static final float F_LOWER = -2048f;
  72.         private static final double D_UPPER = 4096;
  73.         private static final double D_LOWER = -4096;
  74.  
  75.         /**
  76.          * After hours of research I have learned a lot about working with bit-wise
  77.          * operators. <br />
  78.          * This is the sum of my labor, hours of work put into one beautiful class
  79.          * and a few methods
  80.          *
  81.          * @author Matthew Crocco (Treehouse Elite) with Contributions from
  82.          *         StackOverflow (Various Users) and LibGDX OpenSource Code!
  83.          *
  84.          */
  85.         private static class Sine {
  86.                 protected static final float[] valTable = new float[SIN_COUNT];
  87.                 static {
  88.                         for (int i = 0; i < SIN_COUNT; i++)
  89.                                 valTable[i] = (float) Math.sin((i + 0.5) / SIN_COUNT * TAU);
  90.                         for (int i = 0; i < 360; i += 90)
  91.                                 valTable[(int) (i * degIndex) & SIN_MASK] = (float) Math.sin(i
  92.                                                 * degreesToRadians);
  93.                 }
  94.         }
  95.  
  96.         /** Convert degrees to radians */
  97.         public static float toRadians(float degrees) {
  98.                 return degrees * degRad;
  99.         }
  100.  
  101.         /** Convert degrees to radians */
  102.         public static float toRadians(int degrees) {
  103.                 return toRadians(degrees);
  104.         }
  105.  
  106.         /** Convert radians to degrees */
  107.         public static float toDegrees(float radians) {
  108.                 return radians * radDeg;
  109.         }
  110.  
  111.         /** Convert radians to degrees */
  112.         public static float toDegrees(int radians) {
  113.                 return toDegrees(radians);
  114.         }
  115.  
  116.         /** Get the value of sin(radians) in a quick and efficient manner */
  117.         public static float sin(float radians) {
  118.                 return Sine.valTable[(int) (radians * radIndex) & SIN_MASK];
  119.         }
  120.  
  121.         /** Get the value of sin(degrees) in a quick and efficient manner */
  122.         public static float sinD(float degrees) {
  123.                 return Sine.valTable[(int) (degrees * degIndex) & SIN_MASK];
  124.         }
  125.  
  126.         /** Get the value of cos(radians) in a quick and efficient manner */
  127.         public static float cos(float radians) {
  128.                 return Sine.valTable[(int) ((radians + PI / 2) * radIndex) & SIN_MASK];
  129.         }
  130.  
  131.         /** Get value of cos(degrees) in a quick and efficient manner */
  132.         public static float cosD(float degrees) {
  133.                 return Sine.valTable[(int) ((degrees + 90) * degIndex) & SIN_MASK];
  134.         }
  135.  
  136.         public static float tan(float radians) {
  137.                 return sin(radians) / cos(radians);
  138.         }
  139.  
  140.         public static float tanD(float degrees) {
  141.                 return sin(toRadians(degrees)) / cos(toRadians(degrees));
  142.         }
  143.  
  144.         public static float sec(float radians) {
  145.                 return 1 / cos(radians);
  146.         }
  147.  
  148.         public static float csc(float radians) {
  149.                 return 1 / sin(radians);
  150.         }
  151.  
  152.         public static float cot(float radians) {
  153.                 return 1 / tan(radians);
  154.         }
  155.  
  156.         // ----------------------------------------------------------------------
  157.  
  158.         private static final Random r = new Random(); // Decent Pseudorandom Number
  159.                                                                                                         // Generator in my
  160.                                                                                                         // opinion...
  161.  
  162.         /**
  163.          * Returns a random float between [0.0, 1.0)
  164.          */
  165.         public static float random() {
  166.                 return r.nextFloat();
  167.         }
  168.  
  169.         /**
  170.          * Returns a random integer between [0, range] inclusive
  171.          */
  172.         public static int random(int range) {
  173.                 return r.nextInt(range + 1);
  174.         }
  175.  
  176.         /**
  177.          * Returns a random integer between [start, end] inclusive
  178.          */
  179.         public static int random(int start, int end) {
  180.                 return start + r.nextInt(end - start + 1);
  181.         }
  182.  
  183.         /** Returns a random boolean value */
  184.         public static boolean randomBool() {
  185.                 return r.nextBoolean();
  186.         }
  187.  
  188.         /**
  189.          * Returns true if a random value falls below the given chance. False if
  190.          * equal to or greater than that chance.<br />
  191.          * Values must be between [0.0,1.0]
  192.          */
  193.         public static final boolean randomBool(float chance) {
  194.                 return Maths.random() < chance;
  195.         }
  196.  
  197.         /**
  198.          * Returns a random float between [0, range)
  199.          *
  200.          * @param range
  201.          *            - max value (exclusive)
  202.          * @return Random Float
  203.          */
  204.         public static final float random(float range) {
  205.                 return r.nextFloat() * range;
  206.         }
  207.  
  208.         /**
  209.          * Get a random value between [start, end)
  210.          *
  211.          * @param start
  212.          *            - start inclusive
  213.          * @param end
  214.          *            - end exclusive
  215.          * @return Random Float between those two values
  216.          */
  217.         public static final float random(float start, float end) {
  218.                 return start + r.nextFloat() * (end - start);
  219.         }
  220.  
  221.         // ----------------------------------------------------------------
  222.  
  223.         // Interesting Bit-Hack I suppose....
  224.         /**
  225.          * Uses a common bit-hack to efficiently and quickly gather the next highest
  226.          * Power of Two
  227.          *
  228.          * @param value
  229.          *            - starting value
  230.          * @return Next Power Of Two as an int
  231.          */
  232.         public static final int nextPowerOfTwo(int value) {
  233.                 if (value == 0)
  234.                         return 1;
  235.  
  236.                 value--;
  237.                 value |= value >> 1;
  238.                 value |= value >> 2;
  239.                 value |= value >> 4;
  240.                 value |= value >> 8;
  241.                 value |= value >> 16;
  242.                 return value + 1;
  243.         }
  244.  
  245.         /**
  246.          * Uses some Bit-wise magic to efficiently return whether or not a value is
  247.          * a Power of Two (useful for animators and maps which require it!).<br />
  248.          * Particularly helpful for OpenGL where images are a power of two.
  249.          *
  250.          * @param value
  251.          *            - value to test
  252.          * @return True if it is, false if not.
  253.          */
  254.         public static final boolean isPowerOfTwo(int value) {
  255.                 return value != 0 && (value & value - 1) == 0;
  256.         }
  257.  
  258.         // ----------------------------------------------------------------
  259.         // So I was getting inaccurate values so I hit up StackOverflow and they
  260.         // recommended the same values as LibGDX...
  261.         // It still isnt clear to me and I look back seeing a lot of mimics of
  262.         // LibGDX but the Bit stuff I can understand
  263.         // and the Sine stuff but this seems arbitrary, I may still recommend
  264.         // Math.ceil but this SHOULD work.
  265.  
  266.         private static final int BIGINT = 16 * 1024;
  267.         private static final double BIGFLOOR = BIGINT;
  268.         private static final double CEILING = 0.99999999;
  269.         private static final double BIGCEIL = 16384.999999999996;
  270.         private static final double BIGROUND = BIGINT + 0.5f;
  271.  
  272.         /**
  273.          * Floors a float value, all realistic values work fine but certain extreme
  274.          * values are affected by some inaccuracy.
  275.          */
  276.         public static final int floors(float value) {
  277.                 return (int) (value + BIGFLOOR) - BIGINT;
  278.         }
  279.  
  280.         /**
  281.          * Floors a float value, IT MUST BE POSITIVE, all realistic values work fine
  282.          * but extreme values can be somewhat inaccurate.
  283.          */
  284.         public static final int floorPositive(float value) {
  285.                 return (int) value;
  286.         }
  287.  
  288.         /**
  289.          * Uses the less efficient JNI interfacing Math.floor method from
  290.          * java.lang.Math and casts it to an int value.
  291.          *
  292.          * @see java.lang.Math#floor(double) Math.floor(double)
  293.          */
  294.         public static final int floor(float value) {
  295.                 int isolate = Integer.parseInt(Float.toString(value).substring(
  296.                                 Float.toString(value).indexOf('.') + 1,
  297.                                 Float.toString(value).indexOf('.') + 2));
  298.                 if (isolate >= 5)
  299.                         return (int) (value - 0.5);
  300.                 else
  301.                         return (int) value;
  302.         }
  303.  
  304.         /**
  305.          * Gets the ceiling of a float value, all realistic values work fine but
  306.          * extreme values can be somewhat inaccurate.
  307.          */
  308.         public static final int ceils(float value) {
  309.                 return (int) (value + BIGCEIL) - BIGINT;
  310.         }
  311.  
  312.         /**
  313.          * Gets the ceiling of a float value, IT MUST BE POSITIVE, all realistic
  314.          * values work fine but extreme values can be somewhat inaccurate.
  315.          */
  316.         public static final int ceilPositive(float value) {
  317.                 return (int) (value + CEILING);
  318.         }
  319.  
  320.         /**
  321.          * Uses the less efficient, JNI implementing, Math.ceil() method to get the
  322.          * ceiling and then casts it to an int value.
  323.          *
  324.          * @see java.lang.Math#ceil(double) Math.ceil(double)
  325.          */
  326.         public static final int ceil(float value) {
  327.                 int isolate = Integer.parseInt(Float.toString(value).substring(
  328.                                 Float.toString(value).indexOf('.') + 1,
  329.                                 Float.toString(value).indexOf('.') + 2));
  330.                 if (isolate >= 5)
  331.                         return (int) value;
  332.                 else
  333.                         return (int) (value + 0.5);
  334.         }
  335.  
  336.         /**
  337.          * Rounds either up or down to the nearest integer for any float value, all
  338.          * realistic values work fine but extreme values can be somewhat inaccurate.
  339.          */
  340.         public static final long round(float value) {
  341.                 return (long) (value + BIGROUND) - BIGINT;
  342.         }
  343.        
  344.         public static final long round(double value) {
  345.                 return (long)((long) (value + BIGROUND) - BIGROUND);
  346.         }
  347.  
  348.         /**
  349.          * Rounds either up or down to the nearest integer for POSITIVE float
  350.          * values, all realistic values work fine but extreme values can be somewhat
  351.          * inaccurate.
  352.          */
  353.         public static final long roundPositive(float value) {
  354.                 return (long) (value + 0.5f);
  355.         }
  356.  
  357.         /**
  358.          * Round a Float to the nth decimal place (n = places)
  359.          *
  360.          * @param value
  361.          *            - Value to round
  362.          * @param places
  363.          *            - Decimal places to round to
  364.          * @return Value rounded to places-th decimal place.
  365.          */
  366.         public static final float round(float value, int places) {
  367.                 float scientific = 1 * (pow(10, places+1));
  368.                 long mutated = round(value * scientific);
  369.                 return mutated / scientific;
  370.         }
  371.  
  372.         /**
  373.          * Round a Double to the nth decimal place (n = places)
  374.          *
  375.          * @param value
  376.          *            - Value to round
  377.          * @param places
  378.          *            - Decimal places to round to
  379.          * @return Value rounded to places-th decimal place.
  380.          */
  381.         public static final double round(double value, int places) {
  382.                 double scientific = 1 * (pow(10, places+1));
  383.                 long mutated = round(value * scientific);
  384.                 return mutated / scientific;
  385.         }
  386.  
  387.         /**
  388.          * Raise a float to the nth power (n = power)<br />
  389.          * <br />
  390.          * Recently became able to support negative and decimal powers.
  391.          *
  392.          * @param base
  393.          *            - Value to apply an exponent to
  394.          * @param power
  395.          *            - Power of the exponent
  396.          * @return Value raised to the power-th power
  397.          */
  398.         public static final float pow(float base, int power) {
  399.                 if (power == 0)
  400.                         return 1;
  401.                 if (power == 1)
  402.                         return base;
  403.                 if (power == -1)
  404.                         return (1 / base);
  405.  
  406.                 // NOW HANDLES NEGATIVES :D
  407.                 if (power < 0) {
  408.                         return (1 / base)
  409.                                         * pow(base, (power < -1 ? power + 1 : power - power));
  410.                 } else {
  411.                         return base * pow(base, (power > 1 ? power - 1 : power - power));
  412.                 }
  413.         }
  414.  
  415.         /**
  416.          * Raise a float to the nth power (n = power)
  417.          *
  418.          * @param base
  419.          *            - Value to apply an exponent to
  420.          * @param power
  421.          *            - Power of the exponent
  422.          * @return Value raised to the power-th power
  423.          */
  424.         public static final double pow(double base, int power) {
  425.                 if (power == 0)
  426.                         return 1;
  427.                 if (power == 1)
  428.                         return base;
  429.                 if (power == -1)
  430.                         return (1 / base);
  431.  
  432.                 // NOW HANDLES NEGATIVES :D
  433.                 if (power < 0) {
  434.                         return (1 / base)
  435.                                         * pow(base, (power < -1 ? power + 1 : power - power));
  436.                 } else {
  437.                         return base * pow(base, (power > 1 ? power - 1 : power - power));
  438.                 }
  439.         }
  440.  
  441.         private static float orig = 0;
  442.         private static float pastGuess = 0;
  443.  
  444.         /**
  445.          * Get the Square Root of Base and round to the Round-th decimal place. <br />
  446.          * <br />
  447.          * If you try to square root a negative you get an imaginary number, at the
  448.          * moment this yields a return value of -1... <br />
  449.          * <br />
  450.          * I mean... Technically that is correct for....... if you dont think too
  451.          * much.
  452.          *
  453.          * @param base
  454.          *            - Value to get the square root of
  455.          * @param round
  456.          *            - Round to this decimal place. If this = 0 then dont round, if
  457.          *            this = -1 then round to the first integer.
  458.          * @return Square root of base
  459.          */
  460.         public static float sqrt(float base, int round) {
  461.                 if (base < 0)
  462.                         return -1;
  463.                 if (base == 0)
  464.                         return 0;
  465.                 if (orig == 0) {
  466.                         orig = base;
  467.                         double guess = Math.sqrt(Maths.nextPowerOfTwo((int) base));
  468.                         float nextGuess = (float) ((guess + (orig / guess)) / 2);
  469.                         pastGuess = nextGuess;
  470.                         if (nextGuess * nextGuess == orig)
  471.                                 return round > 0 || round == -1 ? (round == -1 ? round(
  472.                                                 nextGuess, 0) : round(nextGuess, round)) : nextGuess;
  473.                         else
  474.                                 return sqrt(nextGuess, round);
  475.                 }
  476.                 float nextGuess = (base + (orig / base)) / 2;
  477.                 if (nextGuess == pastGuess) {
  478.                         orig = 0;
  479.                         pastGuess = 0;
  480.                         return round > 0 || round == -1 ? (round == -1 ? round(nextGuess, 0)
  481.                                         : round(nextGuess, round))
  482.                                         : nextGuess;
  483.                 } else {
  484.                         pastGuess = nextGuess;
  485.                         return sqrt(nextGuess, round);
  486.                 }
  487.         }
  488.  
  489.         /**
  490.          * Get the Suare Root of Base unrounded <br />
  491.          * <br />
  492.          * If you try to square root a negative you get an imaginary number, at the
  493.          * moment this yields a return value of -1... <br />
  494.          *
  495.          * @param base
  496.          *            - Base to get the square root of
  497.          * @return Square Root of base
  498.          */
  499.         public static float sqrt(float base) {
  500.                 return sqrt(base, 0);
  501.         }
  502.  
  503.         private static double exactOrig = 0;
  504.         private static double exactPrevGuess = 0;
  505.  
  506.         /**
  507.          * Get the Square Root of Base and round to the Round-th decimal place. <br />
  508.          * <br />
  509.          * If you try to square root a negative you get an imaginary number, at the
  510.          * moment this yields a return value of -1... <br />
  511.          * <br />
  512.          * I mean... Technically that is correct for....... if you dont think too
  513.          * much.
  514.          *
  515.          * @param base
  516.          *            - Value to get the square root of
  517.          * @param round
  518.          *            - Round to this decimal place. If this = 0 then dont round, if
  519.          *            this = -1 then round to the first integer.
  520.          * @return Square root of base
  521.          */
  522.         public static double sqrt(double base, int round) {
  523.                 if (base < 0)
  524.                         return -1;
  525.                 if (base == 0)
  526.                         return 0;
  527.                 if (exactOrig == 0) {
  528.                         exactOrig = base;
  529.                         double guess = Math.sqrt(Maths.nextPowerOfTwo((int) base));
  530.                         float nextGuess = (float) ((guess + (exactOrig / guess)) / 2);
  531.                         exactPrevGuess = nextGuess;
  532.                         if (nextGuess * nextGuess == exactOrig)
  533.                                 return round > 0 || round == -1 ? (round == -1 ? round(
  534.                                                 (double) nextGuess, 0) : round((double) nextGuess,
  535.                                                 round)) : nextGuess;
  536.                         else
  537.                                 return sqrt((double) nextGuess, round);
  538.                 }
  539.                 double nextGuess = (base + (exactOrig / base)) / 2;
  540.                 if (nextGuess == exactPrevGuess) {
  541.                         exactOrig = 0;
  542.                         exactPrevGuess = 0;
  543.                         return round > 0 || round == -1 ? (round == -1 ? round(nextGuess, 0)
  544.                                         : round(nextGuess, round))
  545.                                         : nextGuess;
  546.                 } else {
  547.                         exactPrevGuess = nextGuess;
  548.                         return sqrt(nextGuess, round);
  549.                 }
  550.         }
  551.  
  552.         /**
  553.          * Get the square root of base, unrounded <br />
  554.          * <br />
  555.          * If you try to square root a negative you get an imaginary number, at the
  556.          * moment this yields a return value of -1... <br />
  557.          *
  558.          * @param base
  559.          *            - Base to get the square root of
  560.          * @return Square Root of Base
  561.          */
  562.         public static double sqrt(double base) {
  563.                 return sqrt(base, 0);
  564.         }
  565.  
  566.         /**
  567.          * finds the cube root of any reasonable number, at extremes extremely
  568.          * inaccurate values will be returned. [x^(1/3)] <br />
  569.          * <br />
  570.          * Actually parses a Float from a Double value that was converted to a
  571.          * String. <br />
  572.          * Process: 3rd Root of value as double -> String -> Float parsed from
  573.          * String <br />
  574.          * <br />
  575.          * This is done to maintain precision since the double method ends up being
  576.          * more accurate.
  577.          *
  578.          * @param value
  579.          *            - Value to get the Cube Root of
  580.          * @return cube root of Value
  581.          */
  582.         public static float cbrt(float value) {
  583.                 return Float.parseFloat(Double.toString(round(xroot(3, (double) value),
  584.                                 6)));
  585.         }
  586.  
  587.         /**
  588.          * Finds the Cube Root of any Reasonable Number, at extremes extremely
  589.          * inaccurate values will be returned. [x^(1/3)] <br />
  590.          * <br />
  591.          * Calls xroot(3, value)
  592.          *
  593.          * @param value
  594.          * @return Cube Root of Value
  595.          */
  596.         public static double cbrt(double value) {
  597.                 return xroot(3, value);
  598.         }
  599.  
  600.         /**
  601.          * Calculates the xth root of any number. As long as the Root is a power of
  602.          * two (i.e. 2, 4, 8, 16, 32, etc.) <br />
  603.          * <br />
  604.          * Uses the fact that any root that is a power of two can be represented as
  605.          * that sqrt of the sqrt of the sqrt and so on. <br/>
  606.          * Example: 4th root of 2 = 2^(1/4) = (2^1/2^1/2) = sqrt(sqrt(2)) <br />
  607.          * Example: 16th root of 2 = 2^(1/16) = (2^1/2^1/2^1/2^1/2) =
  608.          * sqrt(sqrt(sqrt(sqrt(2)))) <br />
  609.          * <br />
  610.          * Currently negative roots are unsupported.
  611.          *
  612.          * @param root
  613.          *            - Root to calculate
  614.          * @param val
  615.          *            - Value to derive root from
  616.          * @return The Xth Root of Val
  617.          */
  618.         public static float rootPowOf2(int root, float val) {
  619.                 if (val < 0)
  620.                         return -1;
  621.                 if (isPowerOfTwo(root) && root != 1) {
  622.                         return rootPowOf2(root / 2, sqrt(val));
  623.                 } else {
  624.                         return val;
  625.                 }
  626.         }
  627.  
  628.         /**
  629.          * Calculates the xth root of any number accurately. As long as the Root is
  630.          * a power of two (i.e. 2, 4, 8, 16, 32, etc.) <br />
  631.          * <br />
  632.          * Uses the fact that any root that is a power of two can be represented as
  633.          * that sqrt of the sqrt of the sqrt and so on. <br/>
  634.          * Example: 4th root of 2 = 2^(1/4) = (2^1/2^1/2) = sqrt(sqrt(2)) <br />
  635.          * Example: 16th root of 2 = 2^(1/16) = (2^1/2^1/2^1/2^1/2) =
  636.          * sqrt(sqrt(sqrt(sqrt(2)))) <br />
  637.          * <br />
  638.          * Currently negative roots are unsupported.
  639.          *
  640.          * @param root
  641.          *            - Root to calculate
  642.          * @param val
  643.          *            - Value to derive root from
  644.          * @return The Xth Root of Val
  645.          */
  646.         public static double rootPowOf2(int root, double val) {
  647.                 if (val < 0)
  648.                         return -1;
  649.                 if (isPowerOfTwo(root) && root != 1) {
  650.                         return rootPowOf2(root / 2, sqrt(val));
  651.                 } else {
  652.                         return val;
  653.                 }
  654.         }
  655.  
  656.         static double prevTestD = Double.NaN;
  657.         static float prevTestF = Float.NaN;
  658.  
  659.         /**
  660.          * Calculates the Xth root of Val between upper and lower using a Binary
  661.          * Search Algorithm. <br />
  662.          * <br />
  663.          * Called by cbrt and xroot. <br />
  664.          * <br />
  665.          * If root < 0 returns Not A Number for Float <br />
  666.          * If root = 0 returns Positive Infinity for Float <br />
  667.          * If root = 1 returns val <br />
  668.          * If root = 2 returns sqrt(val) -- More Accurate <br />
  669.          * If root = 3 returns cbrt(val) -- More Accurate <br />
  670.          *
  671.          * @param root
  672.          *            - Root to Obtain
  673.          * @param val
  674.          *            - Value to get the root Root of
  675.          * @param upper
  676.          *            - Upper Limit (Default uses F_UPPER)
  677.          * @param lower
  678.          *            - Lower Limit (Default uses F_LOWER)
  679.          * @return Xth Root of Val
  680.          */
  681.         private static float calcFloatRoot(int root, float val, float upper,
  682.                         float lower) {
  683.  
  684.                 if (root < 0)
  685.                         return Float.NaN;
  686.                 if (root == 0)
  687.                         return Float.POSITIVE_INFINITY;
  688.                 if (root == 1)
  689.                         return val;
  690.                 if (root == 2)
  691.                         return sqrt(val);
  692.                 if (root == 3)
  693.                         return cbrt(val); // Added due to the weakness of calcFloatRoot
  694.  
  695.                 float mid = (upper + lower) / 2;
  696.                 float test = pow(mid, root);
  697.  
  698.                 if (test == val || test == prevTestF) {
  699.                         prevTestF = Float.NaN;
  700.                         // If we hit the Float Upper Bound try to parse a Float out of
  701.                         // calcDoubleRoot
  702.                         // It has a much higher success rate
  703.                         if (mid == F_UPPER || mid == F_LOWER)
  704.                                 return Float.parseFloat(Double.toString(round(
  705.                                                 calcDoubleRoot(root, val, D_UPPER, D_LOWER), 6)));
  706.                         else
  707.                                 return mid;
  708.                 } else if (test > val) {
  709.                         prevTestF = test;
  710.                         return calcFloatRoot(root, val, mid, lower);
  711.                 } else if (test < val) {
  712.                         prevTestF = test;
  713.                         return calcFloatRoot(root, val, upper, mid);
  714.                 } else {
  715.                         prevTestF = Float.NaN;
  716.                         return mid;
  717.                 }
  718.         }
  719.  
  720.         /**
  721.          * Calculates the Xth root of Val between upper and lower using a Binary
  722.          * Search Algorithm. <br />
  723.          * <br />
  724.          * Called by cbrt and xroot. <br />
  725.          * <br />
  726.          * This method ends up being more accurate and precise than calcFloatRootM<br />
  727.          * <br />
  728.          * If root < 0 returns Not A Number for Double <br />
  729.          * If root = 0 returns Positive Infinity for Double <br />
  730.          * If root = 1 returns val <br />
  731.          * If root = 2 returns sqrt(val) -- More Accurate <br />
  732.          *
  733.          * @param root
  734.          *            - Root to Obtain
  735.          * @param val
  736.          *            - Value to get the root Root of
  737.          * @param upper
  738.          *            - Upper Limit (Default uses D_UPPER)
  739.          * @param lower
  740.          *            - Lower Limit (Default uses D_LOWER)
  741.          * @return Xth Root of Val
  742.          */
  743.         private static double calcDoubleRoot(int root, double val, double upper,
  744.                         double lower) {
  745.                 if (root < 0)
  746.                         return Double.NaN;
  747.                 if (root == 0)
  748.                         return Double.POSITIVE_INFINITY;
  749.                 if (root == 1)
  750.                         return val;
  751.                 if (root == 2)
  752.                         return sqrt(val);
  753.  
  754.                 double mid = (upper + lower) / 2;
  755.                 double test = pow(mid, root);
  756.  
  757.                 if (test == val || test == prevTestD) {
  758.                         prevTestD = Double.NaN;
  759.                         return mid;
  760.                 } else if (test > val) {
  761.                         prevTestD = test;
  762.                         return calcDoubleRoot(root, val, mid, lower);
  763.                 } else if (test < val) {
  764.                         prevTestD = test;
  765.                         return calcDoubleRoot(root, val, upper, mid);
  766.                 } else {
  767.                         prevTestD = Double.NaN;
  768.                         return mid;
  769.                 }
  770.  
  771.         }
  772.  
  773.         /**
  774.          * Returns the Xth root of Val <br />
  775.          * <br />
  776.          * If root < 0 returns Float.NaN <br />
  777.          * If root = 0 returns Float.POSITIVE_INFINITY <br />
  778.          * If root = 1 returns val <br />
  779.          * If root = 2 returns sqrt(val) -- More Accurate <br />
  780.          * If root = 3 returns cbrt(val) -- More Accurate <br />
  781.          * <br />
  782.          * If xth root is obviously inaccurate, derive Float from a Double. (See
  783.          * calcFloatRoot) <br />
  784.          *
  785.          *
  786.          * @param root
  787.          *            - Root to derive
  788.          * @param val
  789.          *            - Value to get the root of
  790.          * @return Xth Root of Val
  791.          */
  792.         public static float xroot(int root, float val) {
  793.                 return calcFloatRoot(root, val, F_UPPER, F_LOWER);
  794.         }
  795.  
  796.         /**
  797.          * Returns the Xth Root of Val <br />
  798.          * <br />
  799.          * If root < 0 returns Double.NaN <br />
  800.          * If root = 0 returns Double.POSITIVE_INFINITY <br />
  801.          * If root = 1 returns val <br />
  802.          * If root = 2 returns sqrt(val) -- More Accurate <br />
  803.          *
  804.          * @param root
  805.          * @param val
  806.          * @return
  807.          */
  808.         public static double xroot(int root, double val) {
  809.                 return calcDoubleRoot(root, val, D_UPPER, D_LOWER);
  810.         }
  811.  
  812.         /**
  813.          * Get the absolute value of any number.
  814.          *
  815.          * @param val
  816.          * @return Absolute Value of Val
  817.          */
  818.         public static float abs(float val) {
  819.                 if (val < 0)
  820.                         return -val;
  821.                 else
  822.                         return val;
  823.         }
  824.  
  825.         /**
  826.          * Get the absolute value of any number.
  827.          *
  828.          * @param val
  829.          * @return Absolute Value of Val
  830.          */
  831.         public static double abs(double val) {
  832.                 if (val < 0)
  833.                         return -val;
  834.                 else
  835.                         return val;
  836.         }
  837.        
  838.         /**
  839.          * Get the absolute value of any number.
  840.          *
  841.          * @param val
  842.          * @return Absolute Value of Val
  843.          */
  844.         public static long abs(long val){
  845.                 if(val < 0)
  846.                         return -val;
  847.                 else
  848.                         return val;
  849.         }
  850.        
  851.         /**
  852.          * Get the absolute value of any number.
  853.          *
  854.          * @param val
  855.          * @return Absolute Value of Val
  856.          */
  857.         public static int abs(int val){
  858.                 if(val < 0)
  859.                         return -val;
  860.                 else
  861.                         return val;
  862.         }
  863.  
  864.         /**
  865.          * Get the decimal log of any number. <br />
  866.          * <br />
  867.          * Works using the Change of Base Formula with the Natural Logarithm. <br />
  868.          * Such that log10(5) = ln(5)/ln(10)
  869.          *
  870.          * @param val
  871.          * @return Decimal Logarithm of Val
  872.          */
  873.         public static double log10(double val) {
  874.                 if (val == 1)
  875.                         return 0;
  876.                 if (val == 10)
  877.                         return 1;
  878.                 return (Math.log(val) / Math.log(10));
  879.         }
  880.  
  881.         /**
  882.          * Get the decimal log of any number. <br />
  883.          * <br />
  884.          * Works using the Change of Base Formula with the Natural Logarithm. <br />
  885.          * Such that log10(5) = ln(5)/ln(10)
  886.          *
  887.          * @param val
  888.          * @return Decimal Logarithm of Val
  889.          */
  890.         public static float log10(float val) {
  891.                 if (val == 1)
  892.                         return 0;
  893.                 if (val == 10)
  894.                         return 1;
  895.                 return (float) (Math.log(val) / Math.log(10));
  896.         }
  897.  
  898.         /**
  899.          * Gets the natural log of any number.
  900.          *
  901.          * @param val
  902.          * @return Natural Logarithm of Val
  903.          */
  904.         public static double ln(double val) {
  905.                 if (val == 1)
  906.                         return 0;
  907.                 // Added since passing my value for Eulers Number caused an
  908.                 // output of 0.9999...94 due to accuracy loss associated
  909.                 // with float <-> double conversions.
  910.                 if (val == E || val == Math.E)
  911.                         return 1;
  912.                 return Math.log(val);
  913.         }
  914.  
  915.         /**
  916.          * Gets the natural log of any number.
  917.          *
  918.          * @param val
  919.          * @return Natural Logarithm of Val
  920.          */
  921.         public static float ln(float val) {
  922.                 if (val == 1)
  923.                         return 0;
  924.                 // Added since passing my value for Eulers Number caused an
  925.                 // output of 0.9999...94 due to accuracy loss associated
  926.                 // with float <-> double conversions.
  927.                 if (val == E || val == Math.E)
  928.                         return 1;
  929.                 return (float) Math.log(val);
  930.         }
  931.  
  932.         /**
  933.          * Get the base logarithm of any number. <br />
  934.          * <br />
  935.          * Works using the Change of Base Formula with the Natural Logarithm.<br />
  936.          * Such that log3.7(12) = ln(12)/ln(3.7)
  937.          *
  938.          * @param base
  939.          * @param val
  940.          * @return The base logarithm of val
  941.          */
  942.         public static double logx(double base, double val) {
  943.                 if (val == 1)
  944.                         return 0;
  945.                 if (val == base)
  946.                         return 1;
  947.                 return ln(val) / ln(base);
  948.         }
  949.  
  950.         /**
  951.          * Get the base logarithm of any number. <br />
  952.          * <br />
  953.          * Works using the Change of Base Formula with the Natural Logarithm.<br />
  954.          * Such that log3.7(12) = ln(12)/ln(3.7)
  955.          *
  956.          * @param base
  957.          * @param val
  958.          * @return The base logarithm of val
  959.          */
  960.         public static float logx(float base, float val) {
  961.                 if (val == 1)
  962.                         return 0;
  963.                 if (val == base)
  964.                         return 1;
  965.                 return ln(val) / ln(base);
  966.         }
  967.  
  968.         /**
  969.          * Calculates The Hypotenuse/Resultant Vector of given X and Y Components
  970.          *
  971.          * @param x
  972.          *            - X Component
  973.          * @param y
  974.          *            - Y Component
  975.          * @return Resultant Vector/Hypotenuse
  976.          */
  977.         public static float hypot(float x, float y) {
  978.                 return sqrt(pow(x, 2) + pow(y, 2));
  979.         }
  980.  
  981.         /**
  982.          * Calculates The Hypotenuse/Resultant Vector of given X and Y Components
  983.          *
  984.          * @param x
  985.          *            - X Component
  986.          * @param y
  987.          *            - Y Component
  988.          * @return Resultant Vector/Hypotenuse
  989.          */
  990.         public static double hypot(double x, double y) {
  991.                 return sqrt(pow(x, 2) + pow(y, 2));
  992.         }
  993.        
  994.         /*public static float hypot(Vector2D vector){
  995.                 return hypot(vector.x, vector.y);
  996.         }*/
  997.        
  998.         private static float hypot(Vector2 vector){
  999.                 return hypot(vector.x, vector.y);
  1000.         }
  1001.  
  1002.         /**
  1003.          * Calculates Resultant Vector of given X and Y Components
  1004.          *
  1005.          * @param x
  1006.          *            - X Component
  1007.          * @param y
  1008.          *            - Y Component
  1009.          * @return Resultant Vector/Hypotenuse
  1010.          */
  1011.         public static float calcMagnitude(float x, float y) {
  1012.                 return hypot(x, y);
  1013.         }
  1014.  
  1015.         /**
  1016.          * Calculates Resultant Vector of given X and Y Components
  1017.          *
  1018.          * @param x
  1019.          *            - X Component
  1020.          * @param y
  1021.          *            - Y Component
  1022.          * @return Resultant Vector/Hypotenuse
  1023.          */
  1024.         public static double calcMagnitude(double x, double y) {
  1025.                 return hypot(x, y);
  1026.         }
  1027.        
  1028.         /*public static float calcMagnitude(Vector2D vector){
  1029.                 return hypot(vector.x, vector.y);
  1030.         }*/
  1031.        
  1032.         /**
  1033.          * Calculate Magnitude of a 2D Vector
  1034.          * @param vector
  1035.          * @return Magnitude of vector
  1036.          */
  1037.         public static float calcMagnitude(Vector2 vector){
  1038.                 return hypot(vector.x, vector.y);
  1039.         }
  1040.  
  1041.         /**
  1042.          * Calculates the Magnitude of a 3D Vector
  1043.          * @param vector
  1044.          * @return Magnitude of vector
  1045.          */
  1046.         public static float calcMagnitude(Vector3 vector){
  1047.                 return sqrt(pow(vector.x, 2) + pow(vector.y, 2) + pow(vector.z, 2));
  1048.         }
  1049.        
  1050.         /**
  1051.          * Clamp a Value between Min and Max
  1052.          * @param val - Value to clamp
  1053.          * @param min - Minumum
  1054.          * @param max - Maximum
  1055.          * @return Scaled Value
  1056.          */
  1057.         public static double clamp(double val, double min, double max){
  1058.                 if(val > max) return max;
  1059.                 if(val < min) return min;
  1060.                 return val;
  1061.         }
  1062.        
  1063.         /**
  1064.          * Clamp a Value between Min and Max
  1065.          * @param val - Value to clamp
  1066.          * @param min - Minumum
  1067.          * @param max - Maximum
  1068.          * @return Scaled Value
  1069.          */
  1070.         public static float clamp(float val, float min, float max){
  1071.                 if(val > max) return max;
  1072.                 if(val < min) return min;
  1073.                 return val;
  1074.         }
  1075.        
  1076.         /**
  1077.          * Clamp a Value between Min and Max
  1078.          * @param val - Value to clamp
  1079.          * @param min - Minumum
  1080.          * @param max - Maximum
  1081.          * @return Scaled Value
  1082.          */
  1083.         public static long clamp(long val, long min, long max){
  1084.                 if(val > max) return max;
  1085.                 if(val < min) return min;
  1086.                 return val;
  1087.         }
  1088.        
  1089.         /**
  1090.          * Clamp a Value between Min and Max
  1091.          * @param val - Value to clamp
  1092.          * @param min - Minumum
  1093.          * @param max - Maximum
  1094.          * @return Scaled Value
  1095.          */
  1096.         public static int clamp(int val, int min, int max){
  1097.                 if(val > max) return max;
  1098.                 if(val < min) return min;
  1099.                 return val;
  1100.         }
  1101.        
  1102.         /**
  1103.          * Clamp a Value between Min and Max
  1104.          * @param val - Value to clamp
  1105.          * @param min - Minumum
  1106.          * @param max - Maximum
  1107.          * @return Scaled Value
  1108.          */
  1109.         public static short clamp(short val, short min, short max){
  1110.                 if(val > max) return max;
  1111.                 if(val < min) return min;
  1112.                 return val;
  1113.         }
  1114.        
  1115.         /**
  1116.          * Normalize a Value to between 0 and 1. <br />
  1117.          * if val > max return 1 <br />
  1118.          * if val < min return 0 <br />
  1119.          * else return scaled value. <br />
  1120.          * @param val - Value to Normalize
  1121.          * @param min - Minimum Value
  1122.          * @param max - Maximum Value
  1123.          * @return
  1124.          */
  1125.         public static float normalize(float val, float min, float max){
  1126.                 if(val > max) return 1;
  1127.                 if(val < min) return 0;
  1128.                 return (val - min)/(max-min);
  1129.         }
  1130.        
  1131.         /**
  1132.          * Normalize a Value to between 0 and 1. <br />
  1133.          * if val > max return 1 <br />
  1134.          * if val < min return 0 <br />
  1135.          * else return scaled value. <br />
  1136.          * @param val - Value to Normalize
  1137.          * @param min - Minimum Value
  1138.          * @param max - Maximum Value
  1139.          * @return
  1140.          */
  1141.         public static float normalize(int val, int min, int max){
  1142.                 if(val > max) return 1;
  1143.                 if(val < min) return 0;
  1144.                 return (val - min)/(max-min);
  1145.         }
  1146.        
  1147.         /**
  1148.          * Normalize a Value to between 0 and 1. <br />
  1149.          * if val > max return 1 <br />
  1150.          * if val < min return 0 <br />
  1151.          * else return scaled value. <br />
  1152.          * @param val - Value to Normalize
  1153.          * @param min - Minimum Value
  1154.          * @param max - Maximum Value
  1155.          * @return
  1156.          */
  1157.         public static double normalize(double val, double min, double max){
  1158.                 if(val > max) return 1;
  1159.                 if(val < min) return 0;
  1160.                 return (val - min)/(max-min);
  1161.         }
  1162.        
  1163.         /**
  1164.          * Normalize a Value to between 0 and 1. <br />
  1165.          * if val > max return 1 <br />
  1166.          * if val < min return 0 <br />
  1167.          * else return scaled value. <br />
  1168.          * @param val - Value to Normalize
  1169.          * @param min - Minimum Value
  1170.          * @param max - Maximum Value
  1171.          * @return
  1172.          */
  1173.         public static float normalize(long val, long min, long max){
  1174.                 if(val > max) return 1;
  1175.                 if(val < min) return 0;
  1176.                 return (val - min)/(max-min);
  1177.         }
  1178.        
  1179.         /**
  1180.          * Normalize a Value to between 0 and 1. <br />
  1181.          * if val > max return 1 <br />
  1182.          * if val < min return 0 <br />
  1183.          * else return scaled value. <br />
  1184.          * @param val - Value to Normalize
  1185.          * @param min - Minimum Value
  1186.          * @param max - Maximum Value
  1187.          * @return
  1188.          */
  1189.         public static float normalize(short val, short min, short max){
  1190.                 if(val > max) return 1;
  1191.                 if(val < min) return 0;
  1192.                 return (val - min)/(max-min);
  1193.         }
  1194.        
  1195. }
RAW Paste Data
Top