Math.cos Math.sin = Math.HELP

Hello Everyone,
I was hoping to create a JS script to move objects away from common center based upon their current position. I was thinking to use a single selected path item as the center based on its position x/y and width/height. Using this reference point the script would then move away all other path items from this center point based on a desired amount and with uniform increments given their current location from this center. I was thinking cos and sin would be my friend in this case, however they seem to have become my foe instead. ;-)
Does this sound doable? What am I missing, doing wrong, misinterpreting? Below is a non-working attempt, I can't seem to sort things out, perhaps I was close and missed it or maybe I am super way off and its more complex than I thought. However at this point I am confused across my various failed attempts this only being one of them.
Thanks in advance for any assistance and sanity anyone can provide.
// Example failed code, nonworking concept
var docID = app.activeDocument;
var s0 = docID.selection[0];
pID = docID.pathItems;
var xn, yn;
var stepNum = 20;
for (var i = 0; i < pID.length; i++) {
    var p = pID[i];
    var dx = ((s0.position[0] + s0.width) / 2 - (p.position[0] + p.width) / 2);
    var dy = ((s0.position[1] + s0.height) / 2 - (p.position[1] + p.height) / 2);
    xn = Math.cos(Number(dx) * Math.PI / 180)+stepNum;
    yn = Math.sin(Number(dy) * Math.PI / 180)+stepNum;
    var moveMatrix = app.getTranslationMatrix(xn, yn);
    p.transform(moveMatrix);
    stepNum+=stepNum;

Hi W_J_T, here's one way to do what I think you want to do, I commented out the step increment so all items will "explode" the same distance, not sure if that's what you need.
first I'd move the calculation of the Selected object's center out of the loop, you only need to make the math once.
also, (s0.position[0] + s0.width) / 2  has a problem, it will not give you the center, check below
// calculate Selection center position
var cx = s0.position[0] + s0.width/2;
var cy = s0.position[1] + s0.height/2;
then we're going to loop thru all items and calculate their center
        // calculate pathItem's center position
        var px = p.position[0] + p.width/2;
        var py = p.position[1] + p.height/2;
we're going to skip calculating the distance from the selection's center to each item's center, we don't need it for this method, other methods could use this info.
now, your actual question about Sin/Cos
xn = Math.cos(Number(dx) * Math.PI / 180)+stepNum;
sin(angle) and cos(angle) expect angles in Radians, you are not providing any angles in the formula above. We need to calculate the angle between Selection's center and each path's center
        // get the angle formed between selection's center and current path's center
        var angle = get2pointAngle ([cx,cy], [px,py]);
once we have the angle we can apply it to our "Explosion" variable, I'm assuming is stepNum, and get its x and y distance it needs to move away from selection
        // the distance to move is "stepNum" in the same direction as the angle found previously, get x and y vectors
        var dx = stepNum*Math.cos(angle);// distance x
        var dy = stepNum*Math.sin(angle);// distance y
all is left to do is move the paths, here's the whole thing
// Explosion, AKA move all items away from selection
// carlos canto
// http://forums.adobe.com/thread/1382853?tstart=0
var docID = app.activeDocument;
var s0 = docID.selection[0];
pID = docID.pathItems;
var stepNum = 20; // this is the distance to "explode"
// calculate Selection center position
var cx = s0.position[0] + s0.width/2;
var cy = s0.position[1] + s0.height/2;
for (var i = 0; i < pID.length; i++) {
    var p = pID[i];
    // skip selected item
    if (!p.selected) {
        // calculate pathItem's center position
        var px = p.position[0] + p.width/2;
        var py = p.position[1] + p.height/2;
        // get the angle formed between selection's center and current path's center
        var angle = get2pointAngle ([cx,cy], [px,py]);
        // the distance to move is "stepNum" in the same direction as the angle found previously, get x and y vectors
        var dx = stepNum*Math.cos(angle);// distance x
        var dy = stepNum*Math.sin(angle);// distance y
        var moveMatrix = app.getTranslationMatrix(dx, dy);
        p.transform(moveMatrix);
        //stepNum+=stepNum;
// return the angle from p1 to p2 in Radians. p1 is the origin, p2 rotates around p1
function get2pointAngle(p1, p2) {
    var angl = Math.atan2(p2[1] - p1[1], p2[0] - p1[0]);
    if (angl<0) {   // atan2 returns angles from 0 to Pi, if angle is negative it means is over 180 deg or over Pi, add 360 deg or 2Pi, to get the absolute Positive angle from 0-360 deg
        angl = angl + 2*Math.PI;
  return angl;

Similar Messages

  • Math help needed

    I have the following problem:
    I've written some code which should be able to make a object move along a 3d-heading a,b. But the problem is is that it always moves down (v.yp increases) nomatter where i send the auto pilot.
    Can anyone please check the math of this program???
    package fleetcommanderserver;
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    class Base {
      String Name;
      ArrayList TradeList, Banned;
      double balance, xp, yp, zp;
    class Vessel {
      String Name, Type, User, Validation;
      double xp=0, yp=0, zp=0, a=0, b=0, v=0;
      int AutoPilotMode=0, Damage=0, Shields=100, Armor=100;
      ArrayList CmdList=new ArrayList(), Cargo=new ArrayList(), TradeValues=new ArrayList();
    class User {
      String Name, Password, CallSign;
      double score, balance;
      int atBase;
      ArrayList Vessels;
    class TradeItem {
      String Description;
      double Buy, Sell;
      long Quantity;
    public class GameControl {
      ArrayList Bases, Users;
      long rate=100;
      ServerControl sc;
      public GameControl() {
        try {
          String str;
          Bases = new ArrayList();
          Users = new ArrayList();
          ArrayList Items = new ArrayList();
          FileReader fr = new FileReader("/sources/fleetcommanderserver/items.txt");
          BufferedReader br = new BufferedReader(fr);
          while ((str=br.readLine())!=null) {
            Items.add(str.trim());
          fr = new FileReader("/sources/fleetcommanderserver/src/fleetcommanderserver/basenames.txt");
          br = new BufferedReader(fr);
          while ((str = br.readLine())!=null) {
            Base b = new Base();
            b.Name = str.trim();
            b.xp = (Math.random() -.5)*1e10;
            b.yp = (Math.random() -.5)*1e10;
            b.zp = (Math.random() -.5)*1e10;
            b.balance = 1e18;
            b.TradeList = new ArrayList();
            for (int a=0; a<Items.size(); a++) {
              TradeItem i = new TradeItem();
              i.Description=(String)Items.get(a);
              i.Buy=(Math.random()*1e3);
              i.Sell=(Math.random()*1e3);
              i.Quantity=0;
              b.TradeList.add(i);
            b.Banned = new ArrayList();
            Bases.add(b);
          fr.close();
          fr = new FileReader("/sources/fleetcommanderserver/users.txt");
          br = new BufferedReader(fr);
          int a, b, c=10;
          while ((str = br.readLine())!=null) {
            User u = new User();
            a = 0;
            while (str.charAt( (int) a) != 32) a++;
            u.Name = str.substring(0,a);
            a++;
            b = a;
            while (str.charAt( (int) a) != 32) a++;
            u.Password = str.substring(b, a );
            a++;
            b = a;
            while (str.charAt( (int) a) != 32) a++;
            String s = str.substring(b, a );
            u.balance = Double.valueOf(s).doubleValue();
            u.score = 0;
            u.atBase = (int) (Math.random()*Bases.size()+1);
            u.Vessels = new ArrayList();
            Vessel v=new Vessel();
            v.Name="Vessel" + c++;
            u.Vessels.add(v);
            Users.add(u);
          CalcProgress cp = new CalcProgress ((GameControl)this);
          Timer t1 = new Timer();
          t1.scheduleAtFixedRate(cp, 0, rate);
        } catch (Exception e) {
          e.printStackTrace();
          System.exit(1);
    class CalcProgress
        extends TimerTask
        implements Runnable {
      GameControl gc;
      public CalcProgress(GameControl GC) {
        gc = GC;
      public void run() {
        int a, b;
        for (a = 0; a < gc.Users.size(); a++) {
          User u = (User) gc.Users.get(a);
          for (b = 0; b < u.Vessels.size(); b++) {
            Vessel v = ( (Vessel) u.Vessels.get(b));
            if (v.CmdList.size() >= 1) {
              String s[] = ((String)v.CmdList.get(0)).split(" ");
              int AutoPilotMode=0;
              if (s[0].equals("goto")) {
                AutoPilotMode=1;
              switch (AutoPilotMode) {
                case 1:
                  Base p=null, q=null;
                  for (int c=0; c<gc.Bases.size(); c++) {
                    p = (Base) gc.Bases.get(c);
                    if (s[1].equals(p.Name)) {
                      q=p;
                      break;
                  if(q!=null) {
                    v.a = (Math.atan((q.xp-v.xp)/(q.yp-v.yp))/(2*Math.PI))*360;
                    double r=Math.sqrt((q.xp-v.xp)*(q.xp-v.xp)+(q.yp-v.yp)*(q.yp-v.yp));
                    v.b = (Math.atan(r/(q.zp-v.zp))/(2*Math.PI))*360;
                    v.v = 1000000;
                  break;
            else {
              v.v = 0;
            double k = ((2 * Math.PI) / 360 )* v.a, l = ((2 * Math.PI) / 360 )* v.b;
            double vx = Math.sin(k) * Math.sin(l) * v.v/(double)gc.rate/1000,
                vy = Math.cos(k) * Math.sin(l) * v.v/((double)gc.rate/1000),
                vz = Math.cos(l) * v.v/(double)gc.rate/1000;
            if (vx==Double.NaN) vx=0;
            if (vy==Double.NaN) vy=0;
            if (vz==Double.NaN) vz=0;
            v.xp += vx;
            v.yp += vy;
            v.zp += vz;
    ps. I have checked: vy, vx or vz does nor become a NaN...thx in advance
    gr. Razorblade

    if (vx==Double.NaN) vx=0;
    if (vy==Double.NaN) vy=0;
    if (vz==Double.NaN) vz=0;
    ps. I have checked: vy, vx or vz does nor become a
    NaN...And how did you check? Because the above code will NEVER be true even if, for example, vx is NaN. And that is because NaN != Nan is always true (that is how it is defined to work.)
    You can validate this yourself with the following code....
    System.out.println("result=" + (Double.NaN == Double.NaN)); // false
    System.out.println("result=" + (Double.NaN != Double.NaN)); // true

  • Need math help, bit rates

    Sorry, I know this should be in the compressor or DVD SP forum, but there isn't enough traffic there and I need this ASAP. Hope someone knows bitrate calculations well. I have a file. The total bitrate is 7.15Mb/s. THe audio is 224Kb/s at 48KHz ac3. what is the video average bitrate?
    Streamclip tells me the video is 8Mb/s, so obviously it is a VBR file, cause if the entire thing is only 7.15, the video can't be 8 down the whole thing. So I need the average bitrate to match another file that I have yet to compress.
    Matt
    p.s. I wouldn't mind learning to fish as well, if you are so inclined...
    Message was edited by: RedTruck

    Hey,
    Thanks for the reply. The file was given to me on a DVD. I have permission to rip and re-burn along with another file that I am creating. It is obviously MPEG2, but I already ripped and demuxed, so I now have the m2v.
    I have another movie going on the same track (has to be a track so I can make a story in Studio Pro and have smooth playback for a presentation.)
    Using MPEG Streamclip for diagnosis, the m2v is 8 Mbs. The audio file is ac3 at 224 Kbs. The entire movie clocked out at 7.15 Mbs. So I need to calculate the average bit rate for the video so I can encode my movie at the same rate.
    The whole 1024 bits to bytes and 4.7GB on a disk which is actually 4.38... ah... bloowey... I can't figure out exactly the bit rate so they will fit in the same track. I am actually re-encoding her movie right now so I can just duplicate the setting. But I would still like to know how to get an accurate calculation for the future. I have had to do this before and I always wind up wasting time re-encoding.
    Thanks for any help you can give.
    Matt

  • Math help: calibrating adxl375

    I have to 12 point calibration of adxl375. I have attached a datasheet of the method. Page 7 shows the equation 1 which i have to solve.
    It has 12 known.
    We keep sensor in six different poisition, each generate 3 set of equations to fit in the matrix. Equations arre below. I have filled value of Ax,Ay,Az:
    How to solve that in labview??
    /* +z axis */
    a11*30 + a12*50 + a13*2548 + o1 = 0
    a21*30 + a22*50 + a23*2548 + o2 = 0
    a31*30 + a32*50 + a33*2548 + o3 = 1
    /* -z axis */
    a11*20 + a12*10 + a13*980+ o1 = 0
    a21*20 + a22*10 + a23*980 + o2 = 0
    a31*20 + a32*10 + a33*980 + o3 = -1
    /* +y axis */
    a11*30 + a12*1911 + a13*50 + o1 = 0
    a21*30 + a22*1911 + a23*50 + o2 = 1
    a31*30 + a32*1911 + a33*50 + o3 = 0
    /* -y axis */
    a11*20 + a12*49 + a13*10+ o1 = 0
    a21*20 + a22*49 + a23*10 + o2 = -1
    a31*20 + a32*49 + a33*10 + o3 = 0
    /* +x axis */
    a11*2303 + a12*30 + a13*50 + o1 = 1
    a21*2303 + a22*30 + a23*50 + o2 = 0
    a31*2303 + a32*30 + a33*50 + o3 = 0
    /* -x axis */
    a11*392 + a12*20 + a13*10+ o1 = -1
    a21*392 + a22*20 + a23*10 + o2 = 0
    a31*392 + a32*20 + a33*10 + o3 = 0
    Attachments:
    DM00119044_2.pdf ‏304 KB

    1. I have made a equation as in attached excel file. Equation has 18 varaibles.
    2. Then I took 6 readings from adxl375 which in turn form 18 equations. 
    Equations are in matrix form in block diagram of labview program attached. 
    3. I am getting error: 20001;  The matrix is rank deficient
    4. I don't know why this error. i have 18 equations & 18 variables.
    5. With error, I still get values in "Solution matrix" in front panel. These values when i put back in equation , I got result as in "AxB" in front panel.
    These values are almost matching result. So not a problem at this stage.
    I want to know is there any more aggressive method to get exact results.
    Attachments:
    matrix.xlsx ‏11 KB
    18 vars.vi ‏15 KB

  • Rotating, need help with cos, and sin.

    I was reading through the fourmns and have learned that I need to convert to degrees. How do I do that? another issue is, the lines are plotted with INT values and can only be int. How do I do this with ints.
    Actually, I have a scale funtion I would like to be float, but the drawRect only accepts ints. Any way of doing this.
    Here is my code. How do I do this properly.
    thanks
    //gets the new points for the rotation. passing in degrees
         public int [] rotation(int vx, int vy, int d, Graphics g)
         //using this to pass the points I need to main
         int [] tp = new int [2];
             //[row] [col]
         int[][] TM = {{Math.cos(d),-Math.sin(d), 0},
                    {Math.sin(d), Math.cos(d), 0},
                    {       0,         0,        1}}; 
             int [][] Op ={{ vx, vy, 1}};
             int [][] TD = new int [1][3];
             //gets the X + TX // Y +TY and 1 value
             TD[0][0] = Op[0][0]*TM[0][0] + Op[0][1]*TM[0][1] + Op[0][2]*TM[0][2];   // {{TX}
             TD[0][1] = Op[0][0]*TM[1][0] + Op[0][1]*TM[1][1] + Op[0][2]*TM[1][2];  //   {TY}
             TD[0][2] = Op[0][0]*TM[2][0] + Op[0][1]*TM[2][1] + Op[0][2]*TM[2][2]; //    {1 }   
             //holds the new cordinate to plot using this cause I dont need the 1
             tp[0] = TD[0][0];
             tp[1] = TD[0][1];
           return tp;
        }

    yeah, here is an example the teacher had. His had 0, and 1's. Im not really sure about it.
    Every math teacher I had skipped trig stuff and cos, sin.
                                                                                              why again?
    | cos90    -sin90      0  |         | 100 |        0  -1   0     |100|      -200
    | sin90      cos90      0 |         | 200 |   =  1   0   0      |200|   =  100
    |   0                0          1  |         |   1   |         0  1    1     |  1   |          1yikes, nothing lined up!! sorry about that. Not sure how to fix it with this little window for edit.
    reilley35

  • Who here uses intel graphics 4400 n experience pixelation problems.  cos I do. pls help

    Help

    [koala@myhost ~]$ lsmod
    Module Size Used by
    uhci_hcd 18764 0
    video 16208 0
    backlight 3652 1 video
    ath_pci 207800 0
    wlan 186612 1 ath_pci
    ath_hal 298208 1 ath_pci
    ath5k 88896 0
    Here is my lsmod...:)

  • HI Please Help me with Zoom of a buffered image

    Hi All,
    Please help,
    I want to zoom the buffered image using Affine Transforms, the code shown below can rotate the buffered image now how to zoom the same buffered image using Affine Transforms.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class RotationBounds extends JPanel implements ActionListener
        BufferedImage image;
        AffineTransform at = new AffineTransform();
        Rectangle2D.Double bounds = new Rectangle2D.Double();
        double theta = 0;
        double thetaInc = Math.PI / 2;
        public void actionPerformed(ActionEvent e)
            theta += thetaInc;
            setTransform();
            repaint();
        private void setTransform()
            int iw = image.getWidth();
            int ih = image.getHeight();
            double cos = Math.abs(Math.cos(theta));
            double sin = Math.abs(Math.sin(theta));
            double width = iw * cos + ih * sin;
            double height = ih * cos + iw * sin;
            double x = (getWidth() - iw) / 2;
            double y = (getHeight() - ih) / 2;
            at.setToTranslation(x, y);
            at.rotate(theta, iw / 2.0, ih / 2.0);
            x = (getWidth() - width) / 2;
            y = (getHeight() - height) / 2;
            // Set bounding rectangle that will frame the image rotated
            // with this transform. Use this width and height to make a
            // new BuffferedImage that will hold this rotated image.
            // AffineTransformOp doesn't have this size information in
            // the translation/rotation transform it receives.
            bounds.setFrame(x - 1, y - 1, width + 1, height + 1);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            setBackground(Color.gray);
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
            if (image == null)
                initImage();
            g2.drawRenderedImage(image, at);
            // g2.setPaint(Color.blue);
            g2.draw(bounds);
            g2.setPaint(Color.green.darker());
            g2.fill(new Ellipse2D.Double(getWidth() / 2 - 2,
                getHeight() / 2 - 2, 4, 4));
        private void initImage()
            int w = 360, h = 300;
            image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(new Color(220, 240, 240));
            g2.fillRect(0, 0, w, h);
            g2.setPaint(Color.red);
            g2.drawString("Text for test", 50, 50);
            g2.drawRect(0, 0, w - 1, h - 1);
            g2.dispose();
            g2.setTransform(at);
    //        setTransform();
        private JPanel getLast()
            JButton rotateButton = new JButton("Rotate");
            rotateButton.addActionListener(this);
             JButton zoomButton = new JButton("Zoom");
            JPanel panel = new JPanel();
            panel.add(rotateButton);
            panel.add(zoomButton);
            return panel;
        public static void main(String[] args)
            RotationBounds test = new RotationBounds();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test);
            f.getContentPane().add(test.getLast(), "North");
            f.setSize(400, 400);
            f.setLocation(0, 0);
            f.setVisible(true);
    }Message was edited by:
    New_to_Java

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.util.Hashtable;
    import javax.swing.*;
    import javax.swing.event.*;
    public class RotationZoom extends JPanel {
        AffineTransform at = new AffineTransform();
        Point2D.Double imageLoc = new Point2D.Double(100.0, 50.0);
        Rectangle2D.Double bounds = new Rectangle2D.Double();
        BufferedImage image;
        double theta = 0;
        double scale = 1.0;
        final int PAD = 20;
        public RotationZoom() {
            initImage();
        public void addNotify() {
            super.addNotify();
            setTransform();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            g2.drawRenderedImage(image, at);
            g2.setPaint(Color.red);
            g2.draw(bounds);
        public Dimension getPreferredSize() {
            return new Dimension((int)(imageLoc.x + Math.ceil(bounds.width))  + PAD,
                                 (int)(imageLoc.y + Math.ceil(bounds.height)) + PAD);
        private void update() {
            setTransform();
            revalidate();
            repaint();
        private void setTransform() {
            int iw = image.getWidth();
            int ih = image.getHeight();
            double cos = Math.abs(Math.cos(theta));
            double sin = Math.abs(Math.sin(theta));
            double width  = iw*cos + ih*sin;
            double height = ih*cos + iw*sin;
            at.setToTranslation(imageLoc.x, imageLoc.y);
            at.rotate(theta, scale*iw/2.0, scale*ih/2.0);
            at.scale(scale, scale);
            double x = imageLoc.x - scale*(width - iw)/2.0;
            double y = imageLoc.y - scale*(height - ih)/2.0;
            bounds.setFrame(x, y, scale*width, scale*height);
        private void initImage() {
            int w = 240, h = 180;
            int type = BufferedImage.TYPE_INT_RGB;
            image = new BufferedImage(w,h,type);
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setBackground(new Color(220,220,240));
            g2.clearRect(0,0,w,h);
            g2.setPaint(Color.red);
            g2.draw(new CubicCurve2D.Double(0, h, w*4/3.0, h/4.0,
                                            -w/3.0, h/4.0, w, h));
            g2.setPaint(Color.green.darker());
            g2.draw(new Rectangle2D.Double(w/3.0, h/3.0, w/3.0, h/3.0));
            g2.dispose();
        private JPanel getControls() {
            JSlider rotateSlider = new JSlider(-180, 180, 0);
            rotateSlider.setMajorTickSpacing(30);
            rotateSlider.setMinorTickSpacing(10);
            rotateSlider.setPaintTicks(true);
            rotateSlider.setPaintLabels(true);
            rotateSlider.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    int value = ((JSlider)e.getSource()).getValue();
                    theta = Math.toRadians(value);
                    update();
            rotateSlider.setBorder(BorderFactory.createTitledBorder("theta"));
            int min = 50, max = 200, inc = 25;
            JSlider zoomSlider = new JSlider(min, max, 100);
            zoomSlider.setMajorTickSpacing(inc);
            zoomSlider.setMinorTickSpacing(5);
            zoomSlider.setPaintTicks(true);
            zoomSlider.setLabelTable(getLabelTable(min, max, inc));
            zoomSlider.setPaintLabels(true);
            zoomSlider.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    int value = ((JSlider)e.getSource()).getValue();
                    scale = value/100.0;
                    update();
            zoomSlider.setBorder(BorderFactory.createTitledBorder("scale"));
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            panel.add(rotateSlider, gbc);
            panel.add(zoomSlider, gbc);
            return panel;
        private Hashtable getLabelTable(int min, int max, int inc) {
            Hashtable<Integer,JComponent> table = new Hashtable<Integer,JComponent>();
            for(int j = min; j <= max; j += inc) {
                JLabel label = new JLabel(String.format("%.2f", j/100.0));
                table.put(new Integer(j), label);
            return table;
        public static void main(String[] args) {
            RotationZoom test = new RotationZoom();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(test));
            f.getContentPane().add(test.getControls(), "Last");
            f.setSize(500,500);
            f.setLocation(200,100);
            f.setVisible(true);
    }

  • Help needed in class. cant figure out distance

    i have declared 3 variables in a class, x and y are coordiantres
    public class Robot
    private double X;
    private double Y;
    private double Orientation;     
    public Robot()
    X = 0;
    Y = 0;
    Orientation = 0;
    public (double pX, pY, double pOrientation)
    iX = pX;
    iY= pY;
    iOrientation = pOrientation;
    public double getX()
    return iXCoordinate;
    public double getY()
    return iY;
    public double getOrientation()
    return iOrientation;
    public void turnRight (double pDeg) //Degrees
    iOrientation= iOrientation + pDeg;
    public void moveForward (double pDis)
    double d=0;
    double dx=0;
    double dy=0;
    double radians=0;
    radians = Math.toRadians(A); //A is converted to radians     
    dx=d* Math.sin(radians); //distance travelled in x
    dy=d* Math.cos(radians);//distance travelled in y
    how do i get the moveforward i have been given the code written above. in the method also been given dx = d*sin(A) and dy = d*cos(A)
    aprreciate the help thanks

    Damn, I love NetBeans' code reformatting macro...
    public void moveForward(double pDis) {
      double d=0;
      double dx=0;
      double dy=0;
      double radians=0;
      radians = Math.toRadians(A); //A is converted to radians
      dx=d* Math.sin(radians); //distance travelled in x
      dy=d* Math.cos(radians);//distance travelled in y
    }If you read the comments in this method it quite clearly tells you that it is giving you the distances travelled in both dimensions. All you need to do is add those to the objects current position and voila, you have displacement.
    (This is why courses on Newton's laws of motion should be required education for all students)
    McF

  • Class help needed.

    i have declared 3 variables in a class, x and y are coordiantres
    public class Robot
    private double x;
    private double y;
    private double Orientation;
    public Robot()
         x = 0;
         y = 0;
         Orientation = 0;
    public (double px, double py, double pOrientation)
         x = px;
         y= py;
         Orientation = pOrientation;
    public double getX()
    return x;
    public double getY()
    return y;
    public double getOrientation()
    return Orientation;
    public void turnRight (double pDeg) //Degrees
    Orientation= Orientation + pDeg;
    public void moveForward (double pDis)
    how do i get the moveforward i have been given the code written below. in the method also been given dx = d*sin(A) and dy = d*cos(A)
    aprreciate the help thanks
    double d=0;
    double dx=0;
    double dy=0;
    double radians=0;
    radians = Math.toRadians(A); //A is converted to radians
    dx=d* Math.sin(radians); //distance travelled in x
    dy=d* Math.cos(radians);//distance travelled in y
    stuck on what to do there, thanks

    >
    how do i get the moveforward i have been given the
    code written below. in the method also been given dx
    = d*sin(A) and dy = d*cos(A)
    aprreciate the help thanks
    double d=0;
    double dx=0;
    double dy=0;
    double radians=0;
    radians = Math.toRadians(A); //A is converted to
    radians
    dx=d* Math.sin(radians); //distance travelled in x
    dy=d* Math.cos(radians);//distance travelled in y
    A seems to be angle from the x axis that your robot is facing. Therefore replace it with your member variable orientation
    To get your new x, do x = x + dx;
    To get your new y, do y = y + dy;

  • Help with optimize analitics query .

    HI,
    I've got Oracle 10.2.0.3 query like :
    select * from
         select rank() over (partition by t1.customer_key order by
         func(t1.klt_dlugosc,t1.klt_szerokosc,t2.gemfo_dlugosc,t2.gemfo_szerokosc),rownum) as id,
         t1.customer_key,
         func(t1.klt_dlugosc,t1.klt_szerokosc,t2.gemfo_dlugosc,t2.gemfo_szerokosc) odleg_gemfo,
         t2.gemfo_id             
         from tmp_22_geo_0309 t1,
    (select * from adresy_gemfo_geo t2)) where id<3;
    PLAN_TABLE_OUTPUT
    Plan hash value: 187241240
    | Id  | Operation                | Name                           | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT         |                                |    10M|   486M|       |   109K  (2)| 00:25:28 |
    |*  1 |  VIEW                    |                                |    10M|   486M|       |   109K  (2)| 00:25:28 |
    |*  2 |   WINDOW SORT PUSHED RANK|                                |    10M|   630M|  1455M|   109K  (2)| 00:25:28 |
    |   3 |    COUNT                 |                                |       |       |       |            |          |
    |   4 |     MERGE JOIN CARTESIAN |                                |    10M|   630M|       |  9720   (3)| 00:02:17 |
    |   5 |      TABLE ACCESS FULL   | ADRESY_GEMFO_GEO               |   151 |  5738 |       |     3   (0)| 00:00:01 |
    |   6 |      BUFFER SORT         |                                | 66293 |  1812K|       |   109K  (2)| 00:25:28 |
    |   7 |       TABLE ACCESS FULL  | TMP_22_GEO_0309                       | 66293 |  1812K|       |    64   (2)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - filter("ID"<3)
       2 - filter(RANK() OVER ( PARTITION BY "CUSTOMER_KEY" ORDER BY
                  func("KLT_DLUGOSC","KLT_SZEROKOSC","ADRESY_GEMFO_GEO"."GEMFO_DLUGOSC","ADRESY_GEMFO_GEO"."
                  GEMFO_SZEROKOSC"),ROWNUM)<3)
    Note
       - dynamic sampling used for this statement
       is burning CPU , an d runs like 2h
    t1 is 66293 rows
    and t2 is 151 rows
    is there any way to rewrite this ?
    function func is doing some geolocation related math like sin/cos abs .
    Regards.
    Greg

    Yes, thats expected (cartesian join), tables are small .
    Function is doing geolocation calculations like:
    CREATE OR REPLACE function func (dlugosc_geo_1 number,
                                          szerokosc_geo_1 number,
                                          dlugosc_geo_2 number,
                                          szerokosc_geo_2 number) return number
    is
      a_1 number;
      c_1 number;
      d_1 number;
      metry number := 1000;
      r_ziemi number := 6371;
      pi number := 3.1415926535897932384626433832795028841972;
      dLat number;
      dLon number;
      szer_1 number;
      szer_2 number;
    begin
      dLat := abs(szerokosc_geo_2-szerokosc_geo_1)*pi/180;
      dLon := abs(dlugosc_geo_2-dlugosc_geo_1)*pi/180;
      szer_1 := szerokosc_geo_1 * pi/180;
      szer_2 := szerokosc_geo_2 * pi/180;
      a_1 := sin(dLat/2) * sin(dLat/2) +
             cos(szer_1) * cos(szer_2) *
             sin(dLon/2) * sin(dLon/2);
      c_1 := 2 * atan2(sqrt(a_1), sqrt(1-a_1));
      d_1 := round(metry * r_ziemi * c_1);
    RETURN d_1;
    end;
    /

  • Somebody help me out

    Ok this is a jigsaw applet that i added a timer but it keeps on blinking can someone tell me the problem?
    --------Jigsaw.java--------
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.net.*;
    import java.util.*;
    import java.awt.List;
    import java.io.*;
    import java.awt.image.*;
    import java.awt.MediaTracker;
    class JigsawCutter extends RGBImageFilter {
    int dimValue,w,h,overlap;
    int f0,f1,f2,f3,points[];
    boolean grayScale;
    public JigsawCutter(int dVal,boolean gray,int iW,int iH,int oLap,int fc0,int fc1,int fc2,int fc3,int pts[]) {
    dimValue=dVal;
    grayScale=gray;
    overlap=oLap;
    f0=fc0;
    f1=fc1;
    f2=fc2;
    f3=fc3;
    w=iW;
    h=iH;
    points=pts;
    public int filterRGB(int x, int y, int rgb) {
    int r=(rgb>>16) & 0xff;
    int g=(rgb>>8) & 0xff;
    int b=rgb & 0xff;
    int posA,posB;
    int olap2=overlap-3;
    if (dimValue>0) {
    if (grayScale==true) {
    int tv=(int)((r+g+b)/3);
    return(lightenRGB(tv,tv,tv,dimValue));
    } else {
    return(lightenRGB(r,g,b,dimValue));
    } else {
    // ********** HERE IS THE "MAIN" FILTER CODE *************
    int olp=overlap/2;
    int fc0=((f0>=0)?f0:0-f0);
    int fc1=((f1>=0)?f1:0-f1);
    int fc2=((f2>=0)?f2:0-f2);
    int fc3=((f3>=0)?f3:0-f3);
    if (x<olap2) {         // FACE-3
    if (((y<olap2 && f0>0) || (y>=(h-olap2) && f2>0)) || ((y<fc3-olp || y>fc3+olp) && f3>0))
    return(0);
    else {
    if ((y>=fc3-olp && y<=fc3+olp) && f3<0) {
    return(holeCutter(3,fc3,x,y-(fc3-olp),r,g,b));
    if ((y>=fc3-olp && y<=fc3+olp) && f3>0) {
    return(stubCutter(3,fc3,x,y-(fc3-olp),r,g,b));
    } if (x>=w-olap2) {    // FACE-1
    if (((y<olap2 && f0>0) || (y>=(h-olap2) && f2>0)) || ((y<fc1-olp || y>fc1+olp) && f1>0))
    return(0);
    else {
    if ((y>=fc1-olp && y<=fc1+olp) && f1<0) {
    return(holeCutter(1,fc1,x-(w-overlap),y-(fc1-olp),r,g,b));
    if ((y>=fc1-olp && y<=fc1+olp) && f1>0) {
    return(stubCutter(1,fc1,x-(w-overlap),y-(fc1-olp),r,g,b));
    } if (y<olap2) {       // FACE-0
    if (((x<olap2 && f3>0) || (x>=(w-olap2) && f1>0)) || ((x<fc0-olp || x>fc0+olp) && f0>0))
    return(0);
    else {
    if ((x>=fc0-olp && x<=fc0+olp) && f0<0) {
    return(holeCutter(0,fc0,x-(fc0-olp),y,r,g,b));
    if ((x>=fc0-olp && x<=fc0+olp) && f0>0) {
    return(stubCutter(0,fc0,x-(fc0-olp),y,r,g,b));
    } if (y>=h-olap2) {    // FACE-2
    if (((x<olap2 && f3>0) || (x>=(w-olap2) && f1>0)) || ((x<fc2-olp || x>fc2+olp) && f2>0))
    return(0);
    else {
    if ((x>=fc2-olp && x<=fc2+olp) && f2<0) {
    return(holeCutter(2,fc2,x-(fc2-olp),y-(h-overlap),r,g,b));
    if ((x>=fc2-olp && x<=fc2+olp) && f2>0) {
    return(stubCutter(2,fc2,x-(fc2-olp),y-(h-overlap),r,g,b));
    // Enhance the edges
    // =================
    // EDGE 0
    if (((y==0 && f0<0) || (y==overlap-3 && f0>0 && (x<fc0-2 || x>fc0+2)) ))
    return(darkenRGB(r,g,b,15));
    else if (((y==1 && f0<=0) || (y==overlap-2 && f0>0 && (x<fc0-2 || x>fc0+2)) ))
    return(lightenRGB(r,g,b,20));
    else if (((y==2 && f0<=0) || (y==overlap-1 && f0>0 && (x<fc0-2 || x>fc0+2)) ))
    return(lightenRGB(r,g,b,15));
    // EDGE 1
    if (((x==(w-1) && f1<=0) || (((w-1)-x)==overlap-3 && f1>0 && (y<fc1-2 || y>fc1+2)) ))
    return(lightenRGB(r,g,b,20));
    // EDGE 2
    if (((y==(h-1) && f2<=0) || (((h-1)-y)==overlap-3 && f2>0 && (x<fc2-2 || x>fc2+2)) ))
    return(lightenRGB(r,g,b,20));
    // EDGE 3
    if (((x==0 && f3<0) || (x==overlap-3 && f3>0 && (y<fc3-2 || y>fc3+2)) ))
    return(darkenRGB(r,g,b,15));
    else if (((x==1 && f3<=0) || (x==overlap-2 && f3>0 && (y<fc3-2 || y>fc3+2)) ))
    return(lightenRGB(r,g,b,20));
    else if (((x==2 && f3<=0) || (x==overlap-1 && f3>0 && (y<fc3-2 || y>fc3+2)) ))
    return(lightenRGB(r,g,b,15));
    else
    return(rgb);
    private int holeCutter(int face,int fcID,int x,int y,int r,int g,int b) {
    int ol=overlap/2;
    int tp1=0,tp2=0,p1=0,p2=0;
    x++;
    switch (face) {
    case 0: tp1=y; tp2=x-1; p1=0; p2=3; break;
    case 1: tp2=y-1; tp1=x-3; p1=0; p2=2; break;
    case 2: tp1=y-2; tp2=x-1; p1=0; p2=2; break;
    case 3: tp2=y-1; tp1=x-1; p1=0; p2=3; break;
    if (tp1>=p1 && (tp1+p2)<22) {
    if ((tp2>ol-points[tp1+p2]) && (tp2<ol+points[tp1+p2])) {
    //return(0xffff0000);
    return(0);
    } else if ((tp2>=ol-points[tp1+p2]) && (tp2<=ol+points[tp1+p2])) {
    return(darkenRGB(r,g,b,30));
    //return(0xffffff00);
    return (0xff000000 | (r << 16) | (g << 8) | (b << 0));
    private int stubCutter(int face,int fcID,int x,int y,int r,int g,int b) {
    int ol=overlap/2;
    int tp1=0,tp2=0,p1=0,p2=0;
    x++;
    switch (face) {
    case 0: tp1=y; tp2=x-1; p1=0; p2=3; break;
    case 1: tp2=y-1; tp1=x-3; p1=0; p2=2; break;
    case 2: tp1=y-2; tp2=x-1; p1=0; p2=2; break;
    case 3: tp2=y-1; tp1=x-1; p1=0; p2=3; break;
    if (tp1>=p1 && (tp1+p2)<23) {
    if ((tp2>ol-points[tp1+p2]) && (tp2<ol+points[tp1+p2])) {
    //return(0xffffff00);
    return (0xff000000 | (r << 16) | (g << 8) | (b << 0));
    } else if ((tp2>=ol-points[tp1+p2]) && (tp2<=ol+points[tp1+p2])) {
    return(lightenRGB(r,g,b,30));
    //return(0xffff0000);
    return(0);
    private int darkenRGB(int r,int g,int b,int perc) {
    if ((r=(r*(100-perc)/100)-10)<0) r=0;
    if ((g=(g*(100-perc)/100)-10)<0) g=0;
    if ((b=(b*(100-perc)/100)-10)<0) b=0;
    return (0xff000000 | (r << 16) | (g << 8) | (b << 0));
    private int lightenRGB(int r,int g,int b,int perc) {
    if ((r=10+(255-((255-r)*(100-perc)/100)))>255) r=255;
    if ((g=10+(255-((255-g)*(100-perc)/100)))>255) g=255;
    if ((b=10+(255-((255-b)*(100-perc)/100)))>255) b=255;
    return (0xff000000 | (r << 16) | (g << 8) | (b << 0));
    class JigsawPiece extends Canvas {
    Image img;
    int xPos,yPos,basePosX,basePosY,jPosX,jPosY,sizeW,sizeH,overlap,orient;
    Random rNum=new Random();
    int fc[];
    JigsawPiece(Image baseImage,int oLap,int x,int y,int w,int h,int x1,int y1,int x2,int y2,int f0,int f1,int f2,int f3,int pts[],int orientation) {
    basePosX=x+(jPosX=x1);
    basePosY=y+(jPosY=y1);
    xPos=x2;
    yPos=y2;
    fc=new int[4];
    fc[0]=f0;
    fc[1]=f1;
    fc[2]=f2;
    fc[3]=f3;
    orient=orientation;
    if (f0>0) {
    if (f1!=0) {
    if (f1>0) f1+=(oLap-3);
    else f1-=(oLap-3);
    if (f3!=0) {
    if (f3>0) f3+=(oLap-3);
    else f3-=(oLap-3);
    if (f3>0) {
    if (f0!=0) {
    if (f0>0) f0+=(oLap-3);
    else f0-=(oLap-3);
    if (f2!=0) {
    if (f2>0) f2+=(oLap-3);
    else f2-=(oLap-3);
    JigsawCutter jc=new JigsawCutter(0,false,sizeW=w,sizeH=h,overlap=oLap,f0,f1,f2,f3,pts);
    Image tImg=createImage(new FilteredImageSource(baseImage.getSource(),new CropImageFilter(x,y,w,h)));
    img=createImage(new FilteredImageSource(tImg.getSource(),jc));
    setVisible(false);
    public void setPosition(int x,int y) {
    xPos=x;
    yPos=y;
    public void setOrientation(int orientation) {
    if (orientation==0)
    orient=0;
    else {
    orient+=1;
    if (orient>3)
    orient=0;
    public Image getPiece() { return(img);  }
    public int getX() { return(xPos); }
    public int getY() { return(yPos); }
    public int getW() { return(sizeW); }
    public int getH() { return(sizeH); }
    public int getBaseX() { return(basePosX); }
    public int getBaseY() { return(basePosY); }
    public int getFace(int f) { return(fc[f]); }
    public int getOrientation() { return(orient); }
    public boolean isOver(int mX,int mY) {
    //if ((mX>=xPos+overlap && mX<=(xPos+sizeW)-overlap) && (mY>=yPos+overlap && mY<=(yPos+sizeH)-overlap))
    if ((mX>=xPos && mX<=(xPos+sizeW)) && (mY>=yPos && mY<=(yPos+sizeH)))
    return(true);
    else
    return(false);
    public class Jigsaw extends Applet implements Runnable,ActionListener,MouseListener,MouseMotionListener,WindowListener {
    int      wSize,hSize,rows,cols,iWidth,iHeight,jPosX,jPosY,appW,appH,hlpImgFade=-1;
    boolean hlpImgGray=false,avoidCenter=false,canRotate=false,keepClear=false;
    int      autoSnap=3,cutting=0,ts=0,overlap=16,totalPieces,points[],w=0,h=0,vAlign=1;
    Color bgColor=Color.lightGray;
    Color txColor=Color.black;
    Color ofColor=Color.black;
    Color ifColor=Color.black;
    Color pkColor=Color.red;
    Color bdColor=new Color(0xffbfbf);
    boolean showSolve=true;
    Thread runner=null;
    AppletContext apc;
    boolean bDoneSolve=false;
    boolean isComplete=false;
    boolean bImageLoaded=false;
    MediaTracker tracker=new MediaTracker(this);
    int selID=0;
    boolean bCanReorder=true;
    boolean bAutoShow=true;
    Graphics offScrGr;
    Image      offScrImg,img1=null,tImg=null,aImg=null;
    String      imgName,sRunURL,sRunTarget;
    String t[];
    int iOrder[];
    JigsawPiece      jp[],selPP=null;
    Random rNum=new Random();
    int xmOff=0,ymOff=0;
    Label l1,l2,l3;
    Button b1,b2,b3,b4;
    int iNumPieces;
    //Timer2     time;
    Thread Clock_animation;
    private Image Buffer;
    private Graphics gBuffer;
    long currTime;
    long startTime;
    long diffTime;
    long pauseValue;
    long timeSet;
    int hours;
    int minutes;
    int seconds;
    int runner2;
    int soundRunner;
    boolean pressedStart;
    boolean pressedStop;
    boolean pressedReset;
    boolean pressedEnlarge;
    boolean countDown;
    boolean paused;
    boolean enlarged;
    boolean running;
    boolean playSound;
    boolean input;
    boolean blink;
    boolean framed;
    boolean soundDelay;
    int ox;
    int oy;
    double radians;
    double cos;
    double sin;
    Font font1;
    Font font2;
    Font font3;
    Font font4;
    Font font5;
    Color color1;
    Color color2;
    Color bgColor2;
    SpinButton sb1;
    SpinButton sb2;
    SpinButton sb3;
    CheckBox cb1;
    CheckBox cb2;
    CheckBox cb3;
    String message;
    public int STEP_SIZE=20;
    public synchronized void start() {
    if(Clock_animation == null)
    Clock_animation = new Thread(this);
    Clock_animation.start();
    //     StartTimer();
    runner = new Thread();
    runner.start();
         public Jigsaw()
    cos = 1.0D;
    font1 = new Font("Dialog", 0, 14);
    font2 = new Font("Dialog", 1, 11);
    font3 = new Font("Helvetica", 1, 25);
    font4 = new Font("Helvetica", 1, 9);
    font5 = new Font("Helvetica", 1, 16);
    color1 = new Color(25, 55, 135);
    color2 = new Color(225, 225, 225);
    bgColor2 = new Color(0, 0, 0);
    void CalculateTime()
    currTime = System.currentTimeMillis();
    if(!countDown)
    diffTime = (currTime - startTime) / 1000L + pauseValue;
    else
    diffTime = (timeSet - (currTime - startTime)) / 1000L - pauseValue;
    hours = (int)(diffTime - diffTime % 3600L) / 3600;
    minutes = (int)((diffTime - diffTime % 60L) / 60L) % 60;
    seconds = (int)diffTime % 60;
    System.out.println("Time:"+diffTime);
    void StartTimer()
    long h = sb1.GetNumber();
    long m = sb2.GetNumber();
    long s = sb3.GetNumber();
    timeSet = (h * 3600L + m * 60L + s) * 1000L;
    if((!running || paused) && (timeSet != 0L || !countDown))
    paused = false;
    running = true;
    startTime = System.currentTimeMillis();
    void StopTimer()
    if(running)
    if(!paused)
    if(!countDown)
    pauseValue = diffTime;
    else
    pauseValue = (currTime - startTime) / 1000L + pauseValue;
    paused = true;
    void ResetTimer()
    running = false;
    pauseValue = diffTime = 0L;
    startTime = System.currentTimeMillis();
    if(countDown)
    long h = sb1.GetNumber();
    long m = sb2.GetNumber();
    long s = sb3.GetNumber();
    timeSet = (h * 3600L + m * 60L + s) * 1000L;
    hours = (int)h;
    minutes = (int)m;
    seconds = (int)s;
    } else
    hours = minutes = seconds = 0;
    void DrawClock()
    /* if(!blink)
    gBuffer.setColor(Color.red);
    else*/
    //gBuffer.setColor(Color.white);
    //gBuffer.fillRoundRect(38, 45, 112, 30, 15, 15);
    //gBuffer.setFont(font3);
    /* if(!blink)
    gBuffer.setColor(Color.white);
    else*/
    //gBuffer.setColor(Color.black);
    String s1;
    if(hours < 10)
    s1 = "0";
    else
    s1 = "";
    String s2;
    if(minutes < 10)
    s2 = "0";
    else
    s2 = "";
    String s3;
    if(seconds < 10)
    s3 = "0";
    else
    s3 = "";
    String output = s1 + hours + ":" + s2 + minutes + ":" + s3 + seconds;
    if(output.length() <= 8)
              l3.setText(output);
    //gBuffer.drawString(output, 45, 69);
    else
    l3.setText("00:00:00");
    //gBuffer.drawString("00:00:00", 45, 69);
    public synchronized void stop() {
    runner = null;
    if(Clock_animation != null)
    Clock_animation.stop();
    Clock_animation = null;
    StopTimer();
    public void run() {
    Thread me = Thread.currentThread();
    repaint();
    dloadImage(imgName);
    repaint();
    try {
    tracker.waitForID(0);
    } catch (InterruptedException e) {
    return;
    cutupPicture(tImg);
    repaint();
    try {
    tracker.waitForAll();
    } catch (InterruptedException e) {
    return;
    breakupPuzzle(false);
    repaint();     
    addMouseListener(this);
    addMouseMotionListener(this);
    do
    try
    Thread.sleep(100L);
    catch(Exception exception) { }
    runner2++;
    if(runner2 > 5)
         runner2 = 0;
    //if(runner2 < 3)
    //blink = true;
    //else
    // blink = false;
    sb1.Update();
    sb2.Update();
    sb3.Update();
    DrawClock();
    if(!paused && running)
    CalculateTime();
    repaint();
    } while(true);
    public void init() {
    Buffer = createImage(size().width, size().height);
    gBuffer = Buffer.getGraphics();
    font1 = new Font("Dialog", 1, 14);
    sb1 = new SpinButton(99);
    sb2 = new SpinButton(59);
    sb3 = new SpinButton(59);
    currTime = startTime = diffTime = pauseValue = timeSet = 0L;
    //message = getParameter("timer_name");
    /*String clockColorStr = getParameter("clock_color");
    String r = clockColorStr.substring(0, 2);
    String g = clockColorStr.substring(2, 4);
    String b = clockColorStr.substring(4);
    int rt = Integer.parseInt(r, 16);
    int gr = Integer.parseInt(g, 16);
    int bl = Integer.parseInt(b, 16);
    color1 = new Color(rt, gr, bl);
    String bgColorStr = getParameter("bg_color");
    r = bgColorStr.substring(0, 2);
    g = bgColorStr.substring(2, 4);
    b = bgColorStr.substring(4);
    rt = Integer.parseInt(r, 16);
    gr = Integer.parseInt(g, 16);
    bl = Integer.parseInt(b, 16);
    bgColor2 = new Color(rt, gr, bl);*/
    StartTimer();
    sRunURL=null;
    sRunTarget=null;
    //apc=this.getAppletContext();
    if (aImg != null)
    aImg.flush();
    removeMouseListener(this);
    removeMouseMotionListener(this);
    Cursor btnCursor=new Cursor(Cursor.HAND_CURSOR);
    appW=getBounds().width;
    appH=getBounds().height;
    offScrImg = createImage(appW, appH);
    offScrGr = offScrImg.getGraphics();
    setLayout(new FlowLayout(FlowLayout.LEFT,3,3));
    t=new String[4];
    t[0]=new String("Breakup");
    t[1]=new String("Tidy Pieces");
    t[2]=new String("Solve");
    t[3]=new String(" Jigsaw solved ! ");
    readParams();
    if (STEP_SIZE==0)
    STEP_SIZE=makeStepSize(iWidth,iHeight,rows,cols);
    // add(b4=new Button("?"));
    add(l3=new Label("00:00:00"));
    add(b1=new Button(t[0]));
    add(l2=new Label(""));
    add(b2=new Button(t[1]));
    if (showSolve==true) {
    add(b3=new Button(t[2]));
    b3.setCursor(btnCursor);
    b3.addActionListener(this);
    add(l1=new Label(t[3]));
    //sb1 = new SpinButton(110, 280, 99);
    // sb2 = new SpinButton(110, 300, 59);
    //sb3 = new SpinButton(110, 320, 59);
    //add(time=new Timer2());
    //l1.setVisible(false);
    b1.setCursor(btnCursor);
    b2.setCursor(btnCursor);
    //b4.setCursor(btnCursor);
    // b4.setFont(new Font("helvetica",Font.BOLD,13));
    //b4.setForeground(Color.white);
    //b4.setBackground(Color.darkGray);
    b1.addActionListener(this);
    b2.addActionListener(this);
    //b4.addActionListener(this);
    setBackground(bgColor);
    l1.setBackground(bgColor);
    l2.setBackground(bgColor);
    l1.setForeground(txColor);
    l3.setFont(font1);
    l3.setBackground(bgColor);
    l3.setForeground(txColor);
         DrawClock();
    validateKeepClear();
    points=new int[STEP_SIZE+1];
    int lc=0;
    for (double t=0; t<Math.PI; t+=(Math.PI/STEP_SIZE),lc++) {
    double dv=Math.sin(t);
    points[lc]=(int) ((double)((STEP_SIZE-2)/2)*dv);
    totalPieces=rows*cols;
    jPosX=appW-iWidth-7;
    //jPosX=(appW/2)-(iWidth/2);
    switch (vAlign) {
    case 0: jPosY=5; break;
    case 4: jPosX=(appW/2)-(iWidth/2);
    case 1: jPosY=(appH/2)-(iHeight/2); break;
    case 2: jPosY=appH-iHeight-6; break;
    case 3: jPosY=34; break;
    iNumPieces=rows*cols;
    jp=new JigsawPiece[iNumPieces];
    iOrder= new int[iNumPieces];
    System.out.println("Renumber="+iNumPieces);
    repaint();
    public void destroy() {
    if (aImg != null)
    aImg.flush();
    b1.removeActionListener(this);
    b2.removeActionListener(this);
    b3.removeActionListener(this);
    //b4.removeActionListener(this);
    removeMouseListener(this);
    removeMouseMotionListener(this);
    public void actionPerformed(ActionEvent e) {
    String aCmd=e.getActionCommand();
    if (aCmd.equals(t[2])) {
    for (int r=0; r<rows; r++) {
    for (int c=0; c<cols; c++) {
    JigsawPiece pJP=jp[(r*cols)+c];
    pJP.setPosition(pJP.getBaseX(),pJP.getBaseY());
    pJP.setOrientation(0);
    if (aCmd.equals(t[0])) {
    breakupPuzzle(false);
    if (aCmd.equals(t[1])) {
    breakupPuzzle(true);
    // if (aCmd.equals("?")) {
    //showAbout();
    repaint();
    private int makeStepSize(int iW,int iH, int iR,int iC) {
    int iRetVal=16;
    int iPieceW=(int)(iW/iC);
    int iPieceH=(int)(iH/iR);
    int iWork =(iPieceW>iPieceH)?iPieceH:iPieceW;
    if (iWork<28) iRetVal=10;
    else if (iWork<35) iRetVal=12;
    else if (iWork<43) iRetVal=14;
    else if (iWork<50) iRetVal=16;
    else if (iWork<60) iRetVal=18;
    else if (iWork<70) iRetVal=20;
    else if (iWork<80) iRetVal=22;
    else iRetVal=24;
    return iRetVal;
    private void validateKeepClear() {
    w=iWidth/cols;
    h=iHeight/rows;
    int iLeftW=(appW-iWidth-20-overlap);
    int iTopW =(appH-iHeight-20-overlap);
    int iPieceW=(int)(iWidth/cols);
    int iPieceH=(int)(iHeight/rows);
    int iWork=(iPieceW>iPieceH)?iPieceW:iPieceH;
    if ((iWork+5>iLeftW) && (iWork+5> iTopW)) {
    keepClear=false;
    b2.setVisible(false);
    private void breakupPuzzle(boolean onlyTidy) {
    int sPosX=0,sPosY=0;
    int tX=0,tY=0;
    for (int r=0; r<rows; r++) {
    if (bCanReorder)
    reorderList((int)(rNum.nextDouble()*iNumPieces));
    for (int c=0; c<cols; c++) {
    boolean doMe=true;
    JigsawPiece j=jp[(r*cols)+c];
    if (onlyTidy==true) {
    tX=j.getX();
    tY=j.getY();
    if (tX>=jPosX && tX<=((jPosX+iWidth)-w) && tY>=jPosY && tY<=((jPosY+iHeight)-h))
    doMe=false;
    if (doMe==true) {
    do {
    if (!onlyTidy && canRotate) {
    j.setOrientation((int)(rNum.nextDouble()*3));
    sPosX=(int)(rNum.nextDouble()*(appW-w-20-overlap))+10;
    sPosY=(int)(rNum.nextDouble()*(appH-h-20-overlap))+10;
    } while ((keepClear || onlyTidy) && ((sPosX>(jPosX-w-overlap)) && sPosY>=jPosY-h-overlap && sPosY<=jPosY+iHeight));
    j.setPosition(sPosX,sPosY);
    public void dloadImage(String ImgName) {
    try {
    synchronized(this) {
    tImg=(aImg=getImage(new URL(getDocumentBase(),ImgName)).getScaledInstance(iWidth,iHeight,Image.SCALE_FAST));
    tracker.addImage(tImg,0);
    if (hlpImgFade>-1) {
    img1=createImage(new FilteredImageSource(tImg.getSource(),new JigsawCutter(hlpImgFade,hlpImgGray,0,0,0,0,0,0,0,points)));
    //cutupPicture(tImg);
    repaint();
    } catch (MalformedURLException mfue) {
    System.out.println("MalformedURLException: " + mfue);
    private void readParams() {
    String vStr;
    //clrParam=Color.decode(vStr);
    imgName=getParameter("Image");
    if ((vStr=getParameter("ImgWidth")) !=null) iWidth =new Integer(vStr).intValue();
    if ((vStr=getParameter("ImgHeight")) !=null) iHeight=new Integer(vStr).intValue();
    if ((vStr=getParameter("Rows")) !=null) rows=new Integer(vStr).intValue();
    if ((vStr=getParameter("Cols")) !=null) cols=new Integer(vStr).intValue();
    if ((vStr=getParameter("DimHelpImage")) !=null) hlpImgFade=new Integer(vStr).intValue();
    if ((vStr=getParameter("HelpImageGrayed")) !=null) if (vStr.equals("true")) hlpImgGray=true;
    if ((vStr=getParameter("AutoSnap")) !=null) autoSnap=new Integer(vStr).intValue();
    if ((vStr=getParameter("CanRotate")) !=null) if (vStr.equals("true")) canRotate=true;
    if ((vStr=getParameter("KeepBoardClear")) !=null) if (vStr.equals("true")) keepClear=true;
    if ((vStr=getParameter("BgColor")) !=null) bgColor=Color.decode(vStr);
    if ((vStr=getParameter("TextColor")) !=null) txColor=Color.decode(vStr);
    if ((vStr=getParameter("OuterFrameColor")) !=null) ofColor=Color.decode(vStr);
    if ((vStr=getParameter("InnerFrameColor")) !=null) ifColor=Color.decode(vStr);
    if ((vStr=getParameter("BoardColor")) !=null) bdColor=Color.decode(vStr);
    if ((vStr=getParameter("SelectColor")) !=null) pkColor=Color.decode(vStr);
    if ((vStr=getParameter("BreakupText")) !=null) t[0]=new String(vStr);
    if ((vStr=getParameter("TidyText")) !=null) t[1]=new String(vStr);
    if ((vStr=getParameter("SolveText")) !=null) t[2]=new String(vStr);
    if ((vStr=getParameter("MessageText")) !=null) t[3]=new String(vStr);
    if ((vStr=getParameter("RunURL")) !=null) sRunURL=new String(vStr);
    if ((vStr=getParameter("RunTarget")) !=null) sRunTarget=new String(vStr);
    if ((vStr=getParameter("AllowSolve")) !=null) if (vStr.equals("false")) showSolve=false;
    if ((vStr=getParameter("LosePieces")) !=null) if (vStr.equals("true")) bCanReorder=false;
    if ((vStr=getParameter("AutoShowPieces")) !=null) if (vStr.equals("false")) bAutoShow=false;
    if ((vStr=getParameter("PictureAlign")) !=null) {
    if (vStr.equals("top")) vAlign=0;
    if (vStr.equals("spaced")) vAlign=3;
    if (vStr.equals("bottom")) vAlign=2;
    if (vStr.equals("center")) vAlign=4;
    if ((vStr=getParameter("Connector")) !=null) {
    switch(new Integer(vStr).intValue()) {
    case -1: STEP_SIZE= 0; break;
    case 0: STEP_SIZE=16; break;
    case 1: STEP_SIZE=18; break;
    case 2: STEP_SIZE=20; break;
    case 3: STEP_SIZE=22; break;
    case 4: STEP_SIZE=24; break;
    if (autoSnap<0) autoSnap=0;
    if (autoSnap>15) autoSnap=15;
    if (hlpImgFade>100) hlpImgFade=100;
    public void cutupPicture(Image baseImg) {
    int pID=0,xPos=0,yPos=0,xOff=0,yOff=0,yOvr=0,xOvr=0;
    int sPosX=0,sPosY=0;
    int lastAdjX,xAdj;
    int f[]=new int[4];
    int CxPos=w/2;
    int CyPos=h/2;
    int bxOffset=0,byOffset=0;
    overlap=STEP_SIZE-2;
    for (int r=0; r<rows; r++) {
    xPos=0;
    for (int c=0; c<cols; c++) {
    do {
    sPosX=(int)(rNum.nextDouble()*(appW-w-10))+5;
    sPosY=(int)(rNum.nextDouble()*(appH-h-10))+5;
    } while (((sPosX<jPosX+iWidth+5 && sPosX>jPosX-w-5) && (sPosY<jPosY+iHeight+5 && sPosY>jPosY-h-5)) && avoidCenter);
    if (r==0) {       // FACE- 0
    f[0]=0;
    } else {
    JigsawPiece pJP=jp[((r-1)*cols)+(c)];
    f[0]=0-pJP.getFace(2);
    if (c==cols-1) {  // FACE-1
    f[1]=0;
    } else {
    f[1]=((h)/2);
    if (((rNum.nextDouble()*2)-1)<0)
    f[1]=0-f[1];
    if (f[0]>0) {
    if (f[1]>0) f[1]+=(overlap-3);
    else f[1]-=(overlap-3);
    if (r==rows-1) {  // FACE-2
    f[2]=0;
    } else {
    f[2]=((w)/2);
    if (((rNum.nextDouble()*2)-1)<0)
    f[2]=0-f[2];
    if (c==0) {       // FACE- 3
    f[3]=0;
    } else {
    JigsawPiece pJP=jp[((r)*cols)+(c-1)];
    f[3]=0-pJP.getFace(1);
    int o[]=new int[4];
    for (int cnt=0; cnt<4; cnt++) {
    o[cnt]=(f[cnt]>0)?overlap-3:0;
    int orientation=(canRotate)?(int)(rNum.nextDouble()*3):0;
    jp[pID]=new JigsawPiece(baseImg,overlap,xPos-o[3],yPos-o[0],w+o[3]+o[1],h+o[0]+o[2],jPosX,jPosY,sPosX,sPosY,f[0],f[1],f[2],f[3],points,orientation);
    iOrder[pID]=pID;
    tracker.addImage(jp[pID].getPiece(),pID+1);
    pID++;
    xPos+=w;
    yPos+=h;
    cutting=0;
    private void reorderList(int iTopPiece) {
    boolean bFound=false;
    if (iTopPiece>iNumPieces)
    iTopPiece=iNumPieces;
    if (iOrder[iNumPieces-1]!=iTopPiece) {
    System.out.println("looking for "+iTopPiece);
    for (int i=0; i<iNumPieces-1; i++) {
    if (!bFound && iOrder==iTopPiece)
    bFound=true;
    if (bFound==true)
    iOrder[i]=iOrder[i+1];
    if (bFound)
    iOrder[iNumPieces-1]=iTopPiece;
    public void randomizePosition(JigsawPiece j,boolean avoidMiddle) {
    int w=iWidth/cols;
    int h=iHeight/rows;
    int sPosX=0,sPosY=0;
    do {
    sPosX=(int)(rNum.nextDouble()*(appW-w-20-overlap))+10;
    sPosY=(int)(rNum.nextDouble()*(appH-h-20-overlap))+10;
    } while ((sPosX<jPosX+iWidth+5+overlap && sPosX>jPosX-w-5) && (sPosY<jPosY+iHeight+5+overlap && sPosY>jPosY-h-5) && avoidMiddle);
    j.setPosition(sPosX,sPosY);
    //public void start() {
    // repaint();
    /*public void update(Graphics g) {
    paint(g);
    public void paint(Graphics g) {
         g.drawImage(Buffer, 0, 0, this);
    int pID=0;
    isComplete=true;
    offScrGr.setColor(bgColor);
    offScrGr.fillRect(0,0,appW,appH);
    offScrGr.setColor(ofColor);
    offScrGr.drawRect(0,0,appW-2,appH-2);
    if (img1 != null)
    offScrGr.drawImage(img1,jPosX,jPosY,this);
    else {
    offScrGr.setColor(bdColor);
    offScrGr.fillRect(jPosX,jPosY,iWidth,iHeight);
    offScrGr.setColor(ifColor);
    offScrGr.drawRect(jPosX-1,jPosY-1,iWidth+2,iHeight+2);
    for (pID=0; pID<iNumPieces; pID++) {
    JigsawPiece j=jp[iOrder[pID]];
    int xP=j.getX(),yP=j.getY();
    if (tracker.statusID(iOrder[pID]+1, false) == MediaTracker.COMPLETE) {
    Image img=j.getPiece();
    int iWd=img.getWidth(this);
    int iHt=img.getHeight(this);
    switch(j.getOrientation()) {
    case 0: offScrGr.drawImage(img,xP,yP,this); break;
    case 1: offScrGr.drawImage(img,xP,yP,xP+iWd,yP+iHt,iWd,0,0,iHt,this); break;
    case 2: offScrGr.drawImage(img,xP,yP,xP+iWd,yP+iHt,iWd,iHt,0,0,this); break;
    case 3: offScrGr.drawImage(img,xP,yP,xP+iWd,yP+iHt,0,iHt,iWd,0,this); break;
    if (isComplete) {
    if (xP!=j.getBaseX() || yP!=j.getBaseY() || j.getOrientation()!=0)
    isComplete=false;
    if (selPP != null) {
    int xP=selPP.getX(),yP=selPP.getY();
    if (!bCanReorder || bAutoShow) {
    Image img=selPP.getPiece();
    int iWd=img.getWidth(thi

    what happens when you uncomment this?/*public void update(Graphics g) {
    paint(g);

  • Help on autocorrelation

    Hi all, I am doing a project on Heart sound.I am suppose to come up
    with a display showing a real time Heart sound,FFT and Heart Rate.I am
    using NI USB 6008 to collect the data frm my hardware unit.I Managed to
    get all the others except Heart rate.I was told to use auto correlation
    to estimate the heart rate from the Heart sound.I have some problem
    with auto correlation.Anybody can help me troubleshoot my source code
    for me?. I really appreciate ur help.Thanks
    Here,I ve attached my source code.Pls troubleshoot .I have to submitthis project  by this week
    Attachments:
    heartsound.vi ‏490 KB

    In the frequency domain, the Hilbert transform changes the sign of the
    frequency content on the negative side of the spectrum.  The
    simplest example is sine/cosine.  The Hilbert transform of a sine
    wave is a cosine wave and vice versa.  These signals together are
    considered a Hilbert pair.  Just like in the simple sine/cosine
    case, where cos^2 + sin^2 = 1, the same is true for any Hilbert pair.
    Since any signal can be represented as a sum of sines and cosines, then
    the Hilbert transform will generate a signal where each sine is matches
    with a cosine function and every cosine function is matches with a sine
    function.  So if you take your original signal and make it the
    real part of a complex signal and take the Hilbert transformed signal
    and make it the imaginary part of a complex signal (the form is called
    an 'analytic signal'), then the resulting magnitude signal should be
    easier to deal with when trying to do peak detection, which is the
    whole point of the process.
    Randall Pursley

  • Simple sine

    Hi it is me again.
    Let me explain better what Im trying to do. Im trying to create a modulation (qpsk), but I dont want to use the MT Modulation toolkit, because I'm trying to creat it spte byt step.
    1 Step: To create a bit stream 8 bits... (done it)
    2 Step: Slit the bit stream in groups of 2 bits ( done it)
    3 Step: Then the 2 bits are divided. One "goes" trough the Channel I (in phase) and the other goes troug the Channel Q (in quadrature). (done it)
    4 Step: Each bit changes its value, 1 logic= +1 and 0 logic = -1 It means that if bit valued 1 goes trough channel I its changes its value to +1, and if its is a 0, it changes its value to -1, and the same for the channel Q ( done it)
    5 Step: Every bit that goes trough channel I must be multiply by a Sin (wct), so the posible answers comming from Channel I are: +Sin (wct) or - Sin (wct), and every bit that goes trough channel Q must be multiply by a Cos (wct), so the possible answers are +cos(wct) or - cos(wct).
    6 Step: Add the answers of every channel. The possible answers are:
    +sin(wct)+cos(wct)
    +sin(wct)-cos(wct)
    -sin(wct)+cos(wct)
    -sin(wct)-cos(wct)
    By doing all this, I have created a qpsk modulation.
    I have done this by creating a sine wave and a cosine wave.... and then multiply each by -1 or +1 and add them... and it works, but what I want to know is if I could do it diferently because I would like to see the answers or the combinations exactly like e.g sin(wct)+cos(wct).... The reason I want this, is becasuse afterwards I have to demodulate.....
    To demodulate:
    Each combination (sen+cos, sen-cos, etc...) goes, at the same time, again troug a channel I and a channel Q, the combiantion trough channel I, multiplies itself, again for sin(wct), and in channel Q for cos (wct)
    example
    Combination: -Sin(wct)+Cos(wct)
    Channel I: (-sin(wct)+cos(wct))*(sin(wct))
    Channel Q: (-sin(wct)+cos(wct))*(cos(wct))
    Matematically:
    (-sinwct+coswt)(sinwct)=
    (-sinwct)(sinwct)+(coswct)(sinwct)=
    -sin^2(wct)+ (coswct)(sinwct)=
    -1/2(1-coswct)+1/2sen(wc+wc)t+1/2sen(wc-wc)t
    so channel I = -1/2+1/2cos2wct+1/2sen2wct+1/2sen0...
    after filtering 1/2cos2wct+1/2sen2wct and 1/2 sen0 = 0
    The answer is -1/2= 0 logic... or a bit value 0.... it the answer where 1/2 = 1 logic or bit valued 1
    That is what I would like to create.. I dont mind about frecuency or wct does not have a especific value... I just want to be able of doing this. I have done it with waves but at the time of demodulait, it does not work the way I would like.
    Please I hope someone can help me!

    All of that can be done in LabVIEW.
    You need to be careful about keeping track of array indexing since the modulation (I and Q data) arrays may have far fewer elements than the carrier {sin(wct) and cos(wct)} arrays.
    I put together a simple demonstration.  It needs some cleaning up at the output.  I was not particularly careful about preallocating buffer for arrays, so this works OK for small datasets but may not scale well.
    It is also not documented well.  The for loops on the left generate the bit streams and do the I and Q modulation.  On the right the multipliers and filters demodulate the carriers and the while loops decode the result.
    Change the noise levels and the filter frequency to see the effects.
    Lynn 
    Note: I had to add a .txt extension to the file so it would attach.  Please remove that before opening it. 
    Attachments:
    I Q modulator.vi.txt ‏59 KB

  • Sin Fit

    is there a vi for regression fitting of sine functions?  like of the form y=A*sin(2*Pi*f+p*t).
    thank you in advance.
    lucas

    Lucas
    What version of LabVIEW are you using?  Do you have any data you could share?  If you are using LabVIEW 8.0 or later, then there is a VI that could be a real help.  Take a look at Extract Multiple Tones.vi.  This is similar to the Extract Single Tone.vi, except it will find more than one tone.  It is also a diffent algorithm that the single tone extraction.  The DC offset in your signal will appear in the "multiple tone info" output as a very low frequency tone (milli-Hz to micro-Hz).  Even if you continue to use the Nonlinear Curve Fit.vi, this could give you a very good initial guess, particularly for the frequency.
    You also mentioned using a numerical root finder to find the zero crossings.  Given your model (A*sin(wx+p)+b) it seems that you should be able to solve explicitly for x.
    a*Sin(wx+p)+b = 0
    Sin(wx+p) = -b/a
    wx+p = InvSin(-b/a)
    x=(InvSin(-b/a)-p)/w
    This will give one level crossing (level of zero), and adding full periods will give every other crossing, but the alternate crossings are not half-periods from the crossing x, unless the offset in the model is zero. 
    You could view the set of crossings as all x that satisfy:
    a*Sin(wx+p+kPi) = 0 where k is an integer,
    expanding in Sin and Cos:
    a*[Sin(wx+p)*Cos(kPi) + Cos(wx+p)*Sin(kPi)] = 0
    Sin(kPi)=0, so
    aCos(kPi)Sin(wx+p)=0
    let A=aCos(kPi)
    solving for x as before gives:
    x=(InvSin(-b/A)-p)/w
    Using this approach and the Extract Multiple Tones.vi seems to give very good results for the zero crossings on some simple data I tried here (Sine + Gaussian Noise).
    The use of local polynomial models will work but if you can involve the entire dataset in solving for a model then there is more "averaging" of the noise in the data and the results should be more robust.  If your data does not match the model well, or the model changes over the course of the data (non-stationary), then Lynn's approach is better.
    Hope this helps.
    -Jim

  • How can I calculate the frequency of a 2-4Hz three phase sine wave in 50msec?

    I want to calculate the frequency of a sine wave using either all three phases or just one, but I want to know the frequency after 50 msec, I don't want to have to wait for a full period.

    I have a mathematically sound suggestion but I do not know how well it will work in application. Most period measurements measure the time between a full period or several periods to eliminate the error introduced by the measuring device. Essentially the device error is made insignificant.
    Mathematically you can do much more but there is a tradeoff between recording less information and knowing (or assuming) some values. For instance, if one knew the amplitude and could calculate the derivative of the signal, one could calculate the frequency. A sine wave can be represented by the function: A sin (BX)=C , where A is the amplitude, B is the frequency, C is the present measured value. If the equation is solved for X, we get: X=(sin^(-1)(C/A))/B. The d
    erivative of the first equation is AB cos(BX)=C. If the equation for X is now substituted into the second equation, we get, AB cos(B (sin^(-1)(C/A))/B)=C. Solving for B we get B=C/(A cos(sin^(-1)(C/A))). Remember, we already know A and C, so we are done.
    Practically every step and assumption in the above argument introduces possible error which will affect the accuracy of the frequency. Unfortunately it is a trade off and that is why at least a whole period needs to be measured to get an accurate frequency.
    Jeremy Braden
    National Instruments

Maybe you are looking for