/* ===================================================================== */
/** Some auxiliary calculations. All members are static. 
    
    @author Emmanuel Gustin
    @version 1.0
*/    
/* ===================================================================== */
import java.lang.*;

public class AuxMath {

  // --- these are all used for intermediate caching of results ---
  // for TickRound
  private static int subticksnumber = 0;

  // ----------------------------------------------------------------
  /** Rounds a double value to a a suitable value for a tick size.
      This is a number of the form {10, 5, 2.5, 2, 1} * 10 ^ exp.
      Calculates also a suitable number of subticks. This is stored
      as a static member of the class, and returned by GetSubTick.
      @param r  Number to round
      @return Rounded value.
  */
  public static double TickRound(double r) {
    double si, ex, ma, tc;
    int st;
  
    // first case : 0.0
    if (r == 0.0) {
      return(0.0);
    }
    // split into sign, exponent and mantissa
    si = (r > 0.0) ? 1.0 : -1.0;
    r = Math.abs(r);
    ex = (double) ((int) (Math.log(r) / Math.log(10.0)));
    ma = r / Math.pow(10.0, ex);
    // determine factor
    if (ma >= 10.0) {
      tc = 10.0;
      st = 2;
    } else if (ma >=  7.5) {
      tc = 7.5;
      st = 5;
    } else if (ma >=  5.0) {
      tc = 5.0;
      st = 5;
    } else if (ma >=  2.5) {
      tc = 2.5;
      st = 5;
    } else if (ma >=  2.0) {
      tc = 2.0;
      st = 2;
    } else {
      tc = 1.0;
      st = 2;
    }
    // multiply again
    tc = si * tc * Math.pow(10.0, ex);
    // return
    subticksnumber = st;
    return(tc);
  }

  // ----------------------------------------------------------------
  /** Returns the subtick generated by a call to TickRound.
      @return number of subticks
  */
  public static int GetSubTick() {
    return(subticksnumber);
  }

}

