Sin/cos

hey I need my program to run faster and I used to just have sin/cos tables to get values from but I need more accuracy than that. However, I dont think I need as much accuracy as the built in java functions give. I forget the exact formula for it.. its something like 1+e^3/3!+e^5/5! etc.. does anyone know how far the java function goes?

Don't bother writing your own trigonometric functions. If you think your program runs slower by calling them (and my guess is that you haven't tested that hypothesis yet), then just make a lookup table. Have entry 0 contain the sine of 0, entry 1 contain the sine of 0.01 (radians), and so on up to entry 628 containing the sine of 6.28 radians. This table of 629 entries covers the entire circle. You can fill in this table while your program is loading by calling the regular Math.sin method.
Then when you need to calculate the sine of an angle, round it to the nearest 0.01 radians, multiply by 100, and use that integer as an array index to get the sine.

Similar Messages

  • Sin, Cos, Tan problem

    Hi i'm doing textbook problems, i'm practically new to java, and forgive my lack of math skills but I need help.
    I need to write a program that prints the values of the function y=sin(x), z=cos(x), t=tan(x) for 'x' allowing the user to enter the starting degree, ending degree, and specifying the step increments. I'm not allowed to use math methods for calculations.
    I can get most of it working just not the actual math calculations. Any help would be appreciated!

    If you're not allowed to use the Math methods then you'll need to hand craft the sin, cos and tan functions yourself.
    The Taylor Expansions for these babies could be the badgers you're after.
    Try here for an introduction.
    http://mathforum.org/library/drmath/view/53760.html

  • Inverse sin cos and tan

    Hello,
    I was trying to use the the Math class in java but the sin cos and tan functions only take radians, not degrees and there doesn't seem to be any functions for finding the the inverse sin cos or tan. Is there another class for doing this or were sun just in a funny mood when they wrote it ?

    So you missed the methods "asin", "acos", "atan", "toRadians", and "toDegrees" in the API spec how?
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Math.html
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/StrictMath.html
    Note that the to* methods are fairly new additions to the API. Conversion between radians and degrees isn't hard anyway ... multip</B>r divide by 180/Math.PI.

  • ATAN2  geometric function and pasing DECFLOAT34 in Sin, cos and Tan.

    Hello,
    1) Is there any macro,Function module  or any way to use atan2 is a variation of the arctangent function in ABAP
    atan2 is available in C, C++, java but i don't seem to find it in ABAP.
    Further details : --- http://en.wikipedia.org/wiki/Atan2
    2) The current limitation for Sin , Cos and tan  geometric functions is Float.
    I am looking for a way to pass a double (DECFLOAT34) into SIn or Cos.
    I do not want to lose the accuracy by using Float.
    Can this be done ?
    Regards,
    Ajay Kulkarni

    Hello Alvaro,
    I have written the following code for atan2 accordingly but it is not as accurate as i wan't it to be.
    The results are not accurate.
    Regards,
    Ajay K
    method ATAN2.
      DATA :
           xsqr TYPE DECFLOAT34,
           ysqr TYPE DECFLOAT34,
           xysqr TYPE DECFLOAT34,
           xysqrt TYPE DECFLOAT34,
           tempa TYPE DECFLOAT34,
           tempb TYPE DECFLOAT34,
           tempc TYPE DECFLOAT34,
           x TYPE DECFLOAT34,
           y TYPE DECFLOAT34,
           atan2 TYPE f.
      data tempb_float TYPE f.
      data tempd_float TYPE f.
    x = iv_x.
    y = iv_y.
    if x = 0 and y = 0.
    ans not defined
    ELSE.
        xsqr = x * x .
        ysqr = y * y .
        xysqr = xsqr + ysqr.
        xysqrt = sqrt( xysqr ).
        tempa = xysqrt - x.
        tempb = tempa / y .
        tempb_float = tempb.
        tempd_float = atan( tempb_float ).
        tempc = 2 * tempd_float.
        ev_atan2 = tempc.
    ENDIF.
    endmethod.

  • Native sin/cos functions

    hey I was curious how much faster I could make sin/cos functions at the expense of some accuracy. I used a taylor polynomial and found that to the 3rd degree, the results of my function were accurate to about 2 decimal points. By the 5th degree, they were pretty much perfect up till past the 8th decimal, unless youre looking for numbers close to pie/2, which is where the most inaccuracy occurs (still accurate to about the 6th decimal place). I tested this against the native Math.sin function, and found that mine was about twice as fast for 3rd degree, and about 1.5 times faster for 5th degree. However, I got some very strange results when I used large numbers in the calculations, where my results were 16X faster then the native ones. Does anyone know what they use to calculate sin and cos? heres my program and results:
    public class Math
         public static double PIE = 3.14159265358979323846;
         public static double sin(double x)
              if(abs(x) <= PIE)
                   return x-x*x*x/6+x*x*x*x*x/120-x*x*x*x*x*x*x/5040+x*x*x*x*x*x*x*x*x/362880;
              double t = x/PIE;
              x = PIE * (t-(int)t);
                   return x-x*x*x/6+x*x*x*x*x/120-x*x*x*x*x*x*x/5040+x*x*x*x*x*x*x*x*x/362880;
         public static double abs(double n)
              return n<0?-n:n;
         public static void main(String[] args)
              int trials = 10000000;
              long initTime = System.currentTimeMillis();
              long time1 = 0;
              long time2 = 0;
              for(int loop = 0; loop < trials; loop++)
                   java.lang.Math.sin(PIE/trials*loop*2);
              time1 = System.currentTimeMillis()-initTime;
              initTime = System.currentTimeMillis();
              for(int loop = 0; loop < trials; loop++)
                   sin(PIE/trials*loop*2);
              time2 = System.currentTimeMillis()-initTime;
              System.out.println("System runtime: "+time1+"\nMy runtime: "+time2);
    }System runtime: 2015
    My runtime: 1594
              for(int loop = 0; loop < trials; loop++)
                   java.lang.Math.sin(loop);
              for(int loop = 0; loop < trials; loop++)
                   sin(loop);
    ....System runtime: 16453
    My runtime: 1688
    I just thought that was a little strange and was curious if anyone knew what caused it?

         public static double PIE = 3.14159265358979323846;Math.PI isn't good enough for you?
    You can always look in the src.zip at the source code.
    Did you get these polynomial approximations out of Abramowitz and Stegun? If not, go find out what that is.
    Or are these Taylor series approximations that you derived for yourself? I don't think this is a good idea.
    How much expertise do you have in numerical analysis? Can you speak to convergence rate, roundoff, and errors in your formulation? If not, you shouldn't offer it as an alternative.
    I doubt that the folks who wrote the sine and cosine used in java.lang.Math were poor programmers. It's good for you to want to understand the details, but it's naive to think that your Taylor series approximation is such a radical improvement.
    %

  • Solaris 9 Fortran sin & cos

    We have a new server running Solaris 9.
    Our old server ran Solaris 6.
    We find that Fortran sin & cos values are now slightly different for given input values.
    Since both of the Solaris versions use IEEE arithmetic with the same rounding conventions, etc. what has changed??????

    We don't believe going from 32 bits to the 64 bits of Solaris 9 is relevant (and its only in addressing, not calculations - isn't it?).
    There are other differences as well, it was the f77 compiler on Solaris 6, now it is the f90 compiler with the -f77 flag.
    But the basic point is that with IEEE arithmetic and the same rounding conventions there is a correct real*4 value for sin(2.4504421).
    Using "WRITE(6,'(F10.7)') SIN(2.4504421)" on our old machine gave 0.63742417 (hex 3F232E3B) whereas our new machine gives 0.63742411 (hex 3F232E3A).
    One of these answers is WRONG - admittedly only in the final bit, but WRONG.

  • StrictMath sin & cos percision errors

    I was wondering if anyone is getting this problem too?
    double sinTheta=StrictMath.sin(StrictMath.PI);
    Now sinTheta should be 0, cuz sin(PI)= 0, in radians.
    But instead sinTheta is
    1.2246467991473532E-16.
    If anyone else is getting this, out of curiousity , how are you handling it? I was planning on making my own Math class which extends from StrictMath (if not then just a new class) which has a method sin(double angle), and if the value is very close to zero, then i will return a zero.
    Even though this all seems picky, I'm writing test harness for Matrix Rotation methods and they are failing only cuz StrictMath.sin is returning an inconsistent value.

    I was wondering if anyone is getting this problem
    too?
    double sinTheta=StrictMath.sin(StrictMath.PI);
    Now sinTheta should be 0, cuz sin(PI)= 0, in radians.
    But instead sinTheta is
    1.2246467991473532E-16.StrictMath.PI is not the actual number PI, but the closest IEEE floating point number to PI. Therefore, the sine of that number is not exactly zero. Floating point arithmetic is inherently imprecise and you cannot expect exact results from it.

  • 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;

  • Hello everyone,I have a question,how to realize trigonometric function:sin

    I need to use sin to calculate the distance between two points on the earth.
    In orcale it has the functions:SIN,ACOS,SQRT, but in TT the same sentence is wrong.
    Now I have a question:how can I realize SIN.
    Thanks

    Hi 948835,
    TimesTen doesnt have a lot of math functions, therefore you can use the following options:
    - calculate math functions (sin, cos and etc.) on application level. Different programming languages contain a very rich functional for math ( look at java.lang.Math for Java for instance).
    - use "Passthrough" TimesTen feature which provides you an opportunity to execute the query in Oracle instead of TimesTen. It works for In-Memory DB Cache only :(
    Best regards,
    Gennady

  • Math.sin

    I am asked to create a program that takes an angle in degrees convert it into radians and give the sin cos and tan of the angle
    I am unfamiliar with these methods and unsure how to set the method up
    I have looked up the method details for all methods such as
    sin
    {code}public static double sin(double a){code}
    I still do not have any clue, I do not want just an answer, I would rather be guided somewhere that I can figure this out on my own.
    I try to look up the classes and methods on java but i just dont understand, this is my second java class and it still seems like a different lanuguage.
    THanks for any help

    a couple of corrections but I think this is perfect
    the last code i posted after i converted to radians i still used my degree varible to detrimine my cos, sin, and tan
    so i fixed it to use the converted radians
         public static void main(String[] args) {
              // Initialize variables
              double angdeg = 0;
              double csin = 0;
              double ccos = 0;
              double ctan = 0;
              double rad = 0;
              // User Input
              Scanner kb = new Scanner(System.in);
              System.out.print("Enter The Angle in Degrees");
              angdeg = kb.nextDouble();
              // Calculations
              rad = Math.toRadians(angdeg);
              csin = Math.sin(rad);
              ccos = Math.cos(rad);
              ctan = Math.tan(rad);
              // Output
              System.out.printf(" Angle (degs): %4.4f\n Angle (rads):  %6.4f\n Sine: %15.4f\n Cosine: %13.4f\n Tangent: %12.4f\n", angdeg, rad, csin, ccos, ctan);
    }

  • How to draw a line of sin x and its area under the line?

    Hi,
    I know how to draw a line from two points. However, I do not know how to draw a line of function sin(x) and its area under the line. Anyone know where to read or how can I draw it, please help me. Thanks !!
    Calvin

    use Graphics2D:: draw(Shape)
    create a class that implements Shape, and specifically the getPathIterator methods, in these methods you should return a path iterator that follows the sin/cos curve.
    All fairly simple to do.
    rob,

  • How to get a formula from the user from a text box in a webpage

    Hi. I would like to know how to get the formula from the user who enters in a textbox. This formula can have any number of variables starting with a and goes on.
    The complexity of the formula can go upto sin, cos, ln, exp. Also user enters the minimum and maximum values of these variables. Based on a specific algorithm (which I use) I would calculate a *set of values, say 10, for each of these variables, substitute in the formula and based on the result of this formula, I select ONE suitable  value for each of the variables.
    I don't know how to get this formula (which most likely to be different each time) and substitute the values *which I found earlier.
    Kindly help me out in this issue.
    Thanks

    The textbox is the easy part. It's no different than getting a String parameter out of an HTTP request.
    The hard part is parsing the String into a "formula" for evaluation. You'll have to write a parser or find one.
    Google for "Java math expression parser" and see what you get.
    Or write your own with JavaCC.
    %

  • Help Please I am new to programming Java1.3.1

    I am having the following problem with the appletviewer for the following code and screen print of error message. I would greatly aperciate any help i can get.Thanks Adera...
    my e-mail address is [email protected]
    Sorry the screen print will not copy into here so i will type it out.
    java.lang.ClassCastException:Calculator
    at sun.applet.AppletPanel.createApplet(AppletPanel.java:579)
    at sun.applet.AppletPanel.runLoader(AppletPanel.java:515)
    at sun.applet.AppletPanel.run(AppletPanel.java:293)
    at java.lang.Thread.run(Thread.java:484)
    Here is my code..
    //Adera Currie Student Id# 31248
    //Course Title: Internet Programming
    //Due Date: August 13th, 2002
    //calculator.Java
    //Hilltop Library Calculator Java Project
    //import javax.swing.*;
    //import javax.swing.JOptionPane;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    //import java.awt.Container;
    public class Calculator extends JFrame implements ActionListener
    int chioce, i;
    //integer variable to hold stringnums in
    double calcone, calctwo;
    //variables for mouse clicks
    double numone, numtwo, total, holdnum, decimalCount;
    String calctot, calctot1, calctot2, negnum, holdnumonetwo;
    //declare text area
    TextField text1;
    //declare button array
    Button calcbutton[], clear;
    //string array to convert textfield values, string manipulation
    String textfield;
    String bpressedEvaluated;
    //declare panel object
    Panel bpanel,text2,Cpanel;
    //declare variable arrays to hold the name and numbers of the buttons that
    //will be created on the applet
    String bnames[] = {"7","8","9","/","Sin","4","5","6",
    "*","Cos","1","2","3","-","Tan",
    "0",".","=","+","Neg"};
    //arrays for holding the items to check for when the action click event is called
    String holdOperatorVisual[] = {"/","*","-","=","+"};
    String holdNumNames[] = {"0","1","2","3","4","5","6","7","8","9",".","Neg"};
    String holdSciFiVisuals[] = {"Sin","Cos","Tan"};
    //declare boolean values to keep track of numbers and operators either
    //in use or what should be terminated
    boolean operators,operators2;
    boolean firstnum;
    boolean secondnum;
    boolean numberpressed,decimalPressed,negPressed;
    public void init()
    //create the panels to hold applet objects
    bpanel = new Panel();
    text2 = new Panel();
    Cpanel = new Panel();
    //set up the applet layout for the buttons and such
    //BorderLayout layout = new BorderLayout(5,5);
    setLayout(new BorderLayout(5,5));
    //create a container object
    //Container c = this.getContentPane();
    //c.setLayout(new FlowLayout());
    //this.setLayout( new FlowLayout() );
    //set up the panels with layout manager
    bpanel.setLayout( new GridLayout (4,5));
    text2.setLayout(new GridLayout(1,1));
    Cpanel.setLayout(new GridLayout(1,1));
    //create my text field to hold the display for the user
    text1 = new TextField(20);
    //make it so the user cannot enter text from the keyboard
    text1.setEditable(false);
    text1.setBackground(Color.cyan);
    text2.add(text1);
    //add teh panel to the container
    add(text2, BorderLayout.NORTH);
    //instantiate button object
    calcbutton = new Button[bnames.length];
         for ( int i = 0; i < bnames.length; i++ )
    calcbutton[i] = new Button(bnames);
    calcbutton[i].addActionListener(this);
    //(new ActionListener()
         calcbutton[i].setBackground(Color.cyan);
    //add the new button from teh array into the panel for buttons
    bpanel.add(calcbutton[i]);
    //add the button panel to the container object
    add(bpanel, BorderLayout.CENTER);
    //create the clear button to be displayed at the bottom of the screen
    clear = new Button("Clear");
    //add the action listener for this object
    clear.addActionListener(this);
    clear.setBackground(Color.cyan);
    //add the clear button to the panel for the clear button
    Cpanel.add(clear);
    //add the clear button panel to the container
    add(Cpanel, BorderLayout.SOUTH);
         public void actionPerformed(ActionEvent e)
         String bpressed = (e.getActionCommand());
         checkButtonPressed(bpressed);
         if(bpressedEvaluated=="notFound")
    //JOptionPane.showMessageDialog(null, "Invalid button selection!",
    // "System Message", JOptionPane.INFORMATION_MESSAGE);
    public void checkButtonPressed(String valueIn)
              String me;
              String takeValueIn = valueIn;
              double tot=0;
              String tat;
              for (i=0;i<holdNumNames.length;i++)
         if(takeValueIn == holdNumNames[i])
         //if there is a second operator in memory, then clear the contents of the
         //text box and start over adding in new numbers from the user
         if (takeValueIn == ".")
         if (decimalPressed == true)
    //JOptionPane.showMessageDialog(null, "This function cannot be used with any other operatorsdecimalPressed== " + decimalPressed,"System Message.", JOptionPane.INFORMATION_MESSAGE);
    break;
    else
    decimalPressed = true;
    if(takeValueIn == "Neg")
         if(numberpressed == false && negPressed == false)
    negPressed = true;
    takeValueIn = "-";
    else
    break;
    if (operators2 == true)
         String nothing;
         nothing = "";
         text1.setText(nothing);
         operators2 = false;
    //if there is no data in the text box, then set this number as the new text
         if (text1.getText().length() == 0)
    text1.setText(takeValueIn);
    //if there is text contained in the text field, then append this number to
    //to the text field and set the new text view for the user
    else if (text1.getText().length() != 0)
    holdnumonetwo = text1.getText();
    holdnumonetwo += takeValueIn;
    text1.setText(holdnumonetwo);
    numberpressed = true;
    bpressedEvaluated = "Found";
    break;
    for (i=0;i<holdOperatorVisual.length;i++)
    if(takeValueIn == holdOperatorVisual[i])
    if (takeValueIn == "=")
    if (operators == true)
    //convert text to number two for calculation
    numtwo = Double.parseDouble(text1.getText());
    //do the math
    if(calctot1=="-")
    tot = numone-numtwo;
    else if(calctot1=="+")
    tot = numone+numtwo;
    else if(calctot1=="/")
    tot = numone/numtwo;
    else if(calctot1=="*")
    tot = numone*numtwo;
    //convert total to string
    tat = String.valueOf(tot);
    //set the visual value to the screen for the user
    text1.setText(tat);
    //update the new number one to be used in the next calculation
    numone = tot;
    decimalPressed = false;
    negPressed = false;
    numberpressed = false;
    break;
    else
    if (operators != true && text1.getText().length()!= 0)
    calctot1 = takeValueIn;
    numone = Double.parseDouble(text1.getText());
    String t;
    t = "";
    text1.setText(t);
    firstnum = true;
    operators = true;                                    decimalPressed = false;
    negPressed = false;                               numberpressed = false;                                    break;
    else if (operators == true && text1.getText().length()!= 0)
    {                                                                                                                                                     calctot2 = takeValueIn;                                                                                                                                                     numtwo = Double.parseDouble(text1.getText());                                                                                                                                                     //do the math                                                                                                                                                if(calctot1=="-")                                                                                                                                                       {                                                                                                                                                     tot = numone-numtwo;                                                                                                                                                    }                                    else if(calctot1=="+")                                    {                                                                                                                                                        tot = numone+numtwo;                                                                                                                                                        }                                    else if(calctot1=="/")                                    {                                                                                                                                                            tot = numone/numtwo;                                                                                                                                                            }                                    else if(calctot1=="*")                                    {                                                                                                                                                                tot = numone*numtwo;                                                                                                                                                               }                                    //convert total to string                                    tat = String.valueOf(tot);                                    //set the visual value to the screen for the user                                    text1.setText(tat);                               //update the new number one to be used in the next calculation                               numone = tot;                               operators2 = true;                               decimalPressed = false;                               negPressed = false;                               }                               calctot1 = calctot2;                               //set the flags                               firstnum = true;                               decimalPressed = false;                               negPressed = false;                               numberpressed = false;                               bpressedEvaluated = "found";                               break;                               }                          }                     }                          for(i=0;i<holdSciFiVisuals.length;i++)                     {                                                                                                                                                         if(takeValueIn == holdSciFiVisuals[i])                     {                                                                                                                                                        if (text1.getText().length()!= 0 && operators != true)                                                                                                                                                            {                                                                                                                                                               double s=0;                                                                                                                                                                numone = Double.parseDouble(text1.getText());                                                                                                                                                            if(takeValueIn == "Sin")                                                                                                                                                                 s = Math.sin(numone);                                                                                                                                                            if(takeValueIn == "Cos")                                                                                                                                                                  s = Math.cos(numone);                                                                                                                                                            if(takeValueIn == "Tan")                                                                                                                                                                  s = Math.tan(numone);                                                                                                                                                                  firstnum = true;                                                                                                                                                                  String ch;                                                                                                                                                                  ch = String.valueOf(s);                                                                                                                                                                  text1.setText(ch);                                                                                                                                                                  operators2 = true;                                                                                                                                                            }                     else if (operators == true)                     {                                                                                                                                                                 //JOptionPane.showMessageDialog(null, "This function cannot be used with any other operators",                                                                                                                                                          //"System Message", JOptionPane.INFORMATION_MESSAGE);                                                                                                                                                                     break;                                                                                                                                                               }                          bpressedEvaluated = "found";                          decimalPressed = false;                          negPressed = false;                          numberpressed = false;                     }                }                          bpressedEvaluated = "notFound";                     if(takeValueIn == "Clear")
    //reset all the values that are either presently in use, or that will be the
    //first values to be used after the text field is cleared, to start from square one
    numone = 0;
    numtwo = 0;
    //set the flags
    firstnum = false;
    secondnum = false;
    operators = false;
    operators2 = false;
    decimalPressed = false;
    negPressed = false;
    numberpressed = false;
    //declare string to help clear the text field
    String cn;
    cn = "";
    //set the text field to nothing, an empty string
    text1.setText(cn);
         //execute application
         public static void main (String args[])
         Calculator application = new Calculator();
    //     addMouseListener(this);
         application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Adera Currie Student Id# 31248
    //Course Title: Internet Programming
    //Due Date: August 13th, 2002
    //calculator.Java
    //Hilltop Library Calculator Java Project
    //import javax.swing.*;
    //import javax.swing.JOptionPane;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    //import java.awt.Container;
    public class Calculator extends JFrame implements ActionListener
         int chioce, i;
         //integer variable to hold stringnums in
         double calcone, calctwo;
         //variables for mouse clicks
         double numone, numtwo, total, holdnum, decimalCount;
         String calctot, calctot1, calctot2, negnum, holdnumonetwo;
         //declare text area
         TextField text1;
         //declare button array
         Button calcbutton[], clear;
         //string array to convert textfield values, string manipulation
         String textfield;
         String bpressedEvaluated;
         //declare panel object
         Panel bpanel,text2,Cpanel;
         //declare variable arrays to hold the name and numbers of the buttons that
         //will be created on the applet
         String bnames[] = {"7","8","9","/","Sin","4","5","6",
    "*","Cos","1","2","3","-","Tan",
    "0",".","=","+","Neg"};
         //arrays for holding the items to check for when the action click event is called
         String holdOperatorVisual[] = {"/","*","-","=","+"};
         String holdNumNames[] = {"0","1","2","3","4","5","6","7","8","9",".","Neg"};
         String holdSciFiVisuals[] = {"Sin","Cos","Tan"};
         //declare boolean values to keep track of numbers and operators either
         //in use or what should be terminated
         boolean operators,operators2;
         boolean firstnum;
         boolean secondnum;
         boolean numberpressed,decimalPressed,negPressed;
         public Calculator()
              //create the panels to hold applet objects
              bpanel = new Panel();
              text2 = new Panel();
              Cpanel = new Panel();
              //set up the applet layout for the buttons and such
              //BorderLayout layout = new BorderLayout(5,5);
              getContentPane().setLayout(new BorderLayout(5,5));
              //create a container object
              //Container c = this.getContentPane();
              //c.setLayout(new FlowLayout());
              //this.setLayout( new FlowLayout() );
              //set up the panels with layout manager
              bpanel.setLayout( new GridLayout (4,5));
              text2.setLayout(new GridLayout(1,1));
              Cpanel.setLayout(new GridLayout(1,1));
              //create my text field to hold the display for the user
              text1 = new TextField(20);
              //make it so the user cannot enter text from the keyboard
              text1.setEditable(false);
              text1.setBackground(Color.cyan);
              text2.add(text1);
              //add teh panel to the container
              getContentPane().add(text2, BorderLayout.NORTH);
              //instantiate button object
              calcbutton = new Button[bnames.length];
              for ( int i = 0; i < bnames.length; i++ )
                   calcbutton[0] = new Button(bnames[0]);
                   calcbutton[0].addActionListener(this);
                   //(new ActionListener()
                   calcbutton[0].setBackground(Color.cyan);
                   //add the new button from teh array into the panel for buttons
                   bpanel.add(calcbutton[0]);
              //add the button panel to the container object
              getContentPane().add(bpanel, BorderLayout.CENTER);
              //create the clear button to be displayed at the bottom of the screen
              clear = new Button("Clear");
              //add the action listener for this object
              clear.addActionListener(this);
              clear.setBackground(Color.cyan);
              //add the clear button to the panel for the clear button
              Cpanel.add(clear);
              //add the clear button panel to the container
              getContentPane().add(Cpanel, BorderLayout.SOUTH);
              pack();
              show();
         public void actionPerformed(ActionEvent e)
              String bpressed = (e.getActionCommand());
              checkButtonPressed(bpressed);
              if(bpressedEvaluated=="notFound")
                   //JOptionPane.showMessageDialog(null, "Invalid button selection!",
                   // "System Message", JOptionPane.INFORMATION_MESSAGE);
         public void checkButtonPressed(String valueIn)
              String me;
              String takeValueIn = valueIn;
              double tot=0;
              String tat;
              for (i=0;i<holdNumNames.length;i++)
                   if(holdNumNames.equals(takeValueIn + ""))
                        //if there is a second operator in memory, then clear the contents of the
                        //text box and start over adding in new numbers from the user
                        if(takeValueIn == ".")
                             if (decimalPressed == true)
                                  //JOptionPane.showMessageDialog(null, "This function cannot be used with any other operatorsdecimalPressed== " + decimalPressed,"System Message.", JOptionPane.INFORMATION_MESSAGE);
                                  break;
                             else
                                  decimalPressed = true;
                        if(takeValueIn == "Neg")
                             if(numberpressed == false && negPressed == false)
                                  negPressed = true;
                                  takeValueIn = "-";
                             else
                                  break;
                        if (operators2 == true)
                             String nothing;
                             nothing = "";
                             text1.setText(nothing);
                             operators2 = false;
                        //if there is no data in the text box, then set this number as the new text
                        if(text1.getText().length() == 0)
                             text1.setText(takeValueIn);
                        //if there is text contained in the text field, then append this number to
                        //to the text field and set the new text view for the user
                        else if (text1.getText().length() != 0)
                             holdnumonetwo = text1.getText();
                             holdnumonetwo += takeValueIn;
                             text1.setText(holdnumonetwo);
                        numberpressed = true;
                        bpressedEvaluated = "Found";
                        break;
              for (i=0;i<holdOperatorVisual.length;i++)
                   if(holdOperatorVisual.equals(takeValueIn+""))
                        if (takeValueIn == "=")
                             if (operators == true)
                                  //convert text to number two for calculation
                                  numtwo = Double.parseDouble(text1.getText());
                                  //do the math
                                  if(calctot1=="-")
                                       tot = numone-numtwo;
                                  else if(calctot1=="+")
                                       tot = numone+numtwo;
                                  else if(calctot1=="/")
                                       tot = numone/numtwo;
                                  else if(calctot1=="*")
                                       tot = numone*numtwo;
                                  //convert total to string
                                  tat = String.valueOf(tot);
                                  //set the visual value to the screen for the user
                                  text1.setText(tat);
                                  //update the new number one to be used in the next calculation
                                  numone = tot;
                                  decimalPressed = false;
                                  negPressed = false;
                                  numberpressed = false;
                             break;
                        else
                             if (operators != true && text1.getText().length()!= 0)
                                  calctot1 = takeValueIn;
                                  numone = Double.parseDouble(text1.getText());
                                  String t;
                                  t = "";
                                  text1.setText(t);
                                  firstnum = true;
                                  operators = true; decimalPressed = false;
                                  negPressed = false; numberpressed = false; break;
                             else if (operators == true && text1.getText().length()!= 0)
                             { calctot2 = takeValueIn; numtwo = Double.parseDouble(text1.getText()); //do the math if(calctot1=="-") { tot = numone-numtwo; } else if(calctot1=="+") { tot = numone+numtwo; } else if(calctot1=="/") { tot = numone/numtwo; } else if(calctot1=="*") { tot = numone*numtwo; } //convert total to string tat = String.valueOf(tot); //set the visual value to the screen for the user text1.setText(tat); //update the new number one to be used in the next calculation numone = tot; operators2 = true; decimalPressed = false; negPressed = false; } calctot1 = calctot2; //set the flags firstnum = true; decimalPressed = false; negPressed = false; numberpressed = false; bpressedEvaluated = "found"; break; } } } for(i=0;i<holdSciFiVisuals.length;i++) { if(takeValueIn == holdSciFiVisuals) { if (text1.getText().length()!= 0 && operators != true) { double s=0; numone = Double.parseDouble(text1.getText()); if(takeValueIn == "Sin") s = Math.sin(numone); if(takeValueIn == "Cos") s = Math.cos(numone); if(takeValueIn == "Tan") s = Math.tan(numone); firstnum = true; String ch; ch = String.valueOf(s); text1.setText(ch); operators2 = true; } else if (operators == true) { //JOptionPane.showMessageDialog(null, "This function cannot be used with any other operators", //"System Message", JOptionPane.INFORMATION_MESSAGE); break; } bpressedEvaluated = "found"; decimalPressed = false; negPressed = false; numberpressed = false; } } bpressedEvaluated = "notFound"; if(takeValueIn == "Clear")
                                       //reset all the values that are either presently in use, or that will be the
                                       //first values to be used after the text field is cleared, to start from square one
                                       numone = 0;
                                       numtwo = 0;
                                       //set the flags
                                       firstnum = false;
                                       secondnum = false;
                                       operators = false;
                                       operators2 = false;
                                       decimalPressed = false;
                                       negPressed = false;
                                       numberpressed = false;
                                       //declare string to help clear the text field
                                       String cn;
                                       cn = "";
                                       //set the text field to nothing, an empty string
                                       text1.setText(cn);
         //execute application
         public static void main (String args[])
              Calculator application = new Calculator();
              // addMouseListener(this);
              application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

  • How to create a game. Basic steps.

    So, just browsing through these forums, I see many posts by prospective game designers wanting to get started. But many of these questions are so ill-researched or off basis that most people don't even know how to respond.
    So here's a quickie guide on how to get started learning to make a game. Notice I didn't say making a game. First you learn, then you make, or else you'll just get frustrated and quit.
    Here's the basic steps:
    1) You need to learn Java. Seriously, don't even think about writing a game if you don't want to. Get a book. My favorite was one by Ivor Horton. But really, any will do.
    If Java is your first programming language, it is important for you to read through the book carefully and do the excercises. This is for you learn what a "programming language" actually is.
    All a computer can do is add numbers. A computer itself knows nothing about Mario or how to make Mario jump. So YOU have to figure out, just what does Mario have to do with numbers.
    2) Write a simple game, without animation in it.
    My first game was Minesweeper. Other examples include Solitaire, or Poker, etc...
    This teaches you how to organize a "large" program. Organization is important. If you don't organize, you'll begin writing a game, and eventually get stuck because your code is unreadable, and your bugs will be impossible to trace down. You'll be frustrated and quit.
    3) Learn the concepts behind animation and a 2D game.
    I see questions like: "I want to make a game, and I drew Mario. Now how to I make him move?". This is for you people.
    Animation is drawing a bunch of images in rapid succession. And a game, basically is a logic system that decides which animations to play at any given time.
    4) Write a 2D game.
    Now, you are ready to attempt an actual game. I started small and wrote a tetris-esque puzzler as my first game with animation. I suggest you do the same, but if you feel ready you can probably jump into a major project now.
    5) Learn about 3D.
    For those aiming high, you can get started learning the concepts behind 3D now. I suggest you know at least a basic knowledge of trigonometry. This means know your sin, cos, and tan inside out, or else you'll up for a lot of work.
    3D is not like 2D. There are quite a few concepts that you will need to learn, and they're not immediately intuitive. Those who have a stronger math background will progress faster. Those who have a weaker background will find it more difficult. But you'll learn a lot along the way. Nothing teaches trig faster than writing a 3D engine.
    6) Write a 3D engine.
    You're entering the hardcore right about now. Few people on this forum will have experience with this and you'll need to do a lot of thinking. Mainly, just because, there's not many people left to ask.
    Some of you will have some ideas on writing this engine. In this case, I recommend you go ahead and try. You might not succeed, but trying will teach you more than anything else.
    Those that don't quite have it down yet, or those that tried and didn't quite succeed can follow along with a book that takes you through this step. The book that I used was "Java game programming". It has a very in-depth section on 3D.
    7) Make your engine fast.
    This step is probably the hardest of all. If you completed step 6, you'll notice that writing a 3D engine, and writing a fast 3D engine is two almost completely different things.
    Here's when you'll research into various computer science algorithms and techniques in order to speed up your engine. Actually, this is when you'll probably learn the concept of "algorithm".
    This is research! You'll find almost no help at forums for this step. Nothing but hard work.
    I can't comment on more than that, as that's as far as I've gotten so far. But that's the basic roadmap.
    Good luck on your games.
    -Cuppo

    Okay I am going to add a few points since they have come up recently.
    With relation to what you should know with Java.
    Beyond the basics you should get a good grounding in the following
    - threading
    - networking in Java (if applicable)
    Threading
    For threading you can use the concurrency tutorial found here http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html
    Threading is really a must. No kidding. Because you will be unable to do anything performance wise without it. Additionally you can't normally take a non-threaded application and slap threading on it. You need to have a design that incorporates being threaded.
    You also don't want to come up with a design to find out later that it's wrong. Don't be afraid to ask questions about your design in general and as how it relates to threading.
    Making a good multi-threaded application is actually not all that difficult, once you understand it. But this is the thing that seems to trip up alot of people. I see an awful lot of bad threading code in the Java Programming forum. Tip: If you are using Thread Priorities you are doing something wrong!
    Networking
    The Java networking tutorial may be found here http://java.sun.com/docs/books/tutorial/networking/index.html
    This is a basic tutorial though so don't assume you know everything there is to know once you have finished it. If you are serious about your development then I HIGHLY recommend the following book
    http://books.google.com/books?id=l6f1jTB_XCYC&dq=Fundamental+Networking+in+Java&psp=1
    As a bonus the author is a long-time member on these forums and a regular in the Networking forums.
    Networking your program, especially depending on how you will use it is important to design into your game from the get-go. If you are planning to make a multi-player online game you need to know what the limitations are with regards to performance early in your development. If you build a beautiful game but it runs like a dog because of what you did in your networking code it would be a real shame and worse it may not be fixable.
    Again don't be afraid to ask questions.
    Restatement of CuppoJava's Comments
    This is a good thread and that's why I am adding these comments to it. I would also say that I totally agree with the sentiments on what you should expect.
    If you are new to Java and expect that in just a few months you are going to crank out a game with a custom 3-d engine you are in for a nasty surprise.
    It isn't that we want to be discouraging, but please do try and set yourself realistic goals and time deadlines. You'll find it a much more positive experience and the less frustrated you are the more likely we are to be able to help you. :)

  • How to find out the coordinates of rotated textframe

    Hi All,
    With the help of (idml) itemtransform horizontal / vertical distances and path point arrays, I can find out the coordinates of text frame (x1,y1), (x2,y2), (x3,y3), (x4,y4). If the textframe is rotated then item transform values are getting changed, but the path point array values are same. I can find rotation angle by the matrix [cos(θ) sin(θ) -sin(θ) cos(θ) 0 0], But I could not get the exact coordinates of rotated textframe. The textframes are given below.
    Normal Text frame
    <TextFrame Self="u136" ParentStory="u124" ItemTransform="1 0 0 1 101.72727272727272 -349.41818181818184">
                <Properties>
                    <PathGeometry>
                        <GeometryPathType PathOpen="false">
                            <PathPointArray>
                                <PathPointType Anchor="-101.72727272727272 -46.581818181818164" LeftDirection="-101.72727272727272 -46.581818181818164" RightDirection="-101.72727272727272 -46.581818181818164"/>
                                <PathPointType Anchor="-101.72727272727272 -0.3272727272727103" LeftDirection="-101.72727272727272 -0.3272727272727103" RightDirection="-101.72727272727272 -0.3272727272727103"/>
                                <PathPointType Anchor="115.9090909090909 -0.3272727272727103" LeftDirection="115.9090909090909 -0.3272727272727103" RightDirection="115.9090909090909 -0.3272727272727103"/>
                                <PathPointType Anchor="115.9090909090909 -46.581818181818164" LeftDirection="115.9090909090909 -46.581818181818164" RightDirection="115.9090909090909 -46.581818181818164"/>
                            </PathPointArray>
                        </GeometryPathType>
                    </PathGeometry>
                </Properties>         
    </TextFrame>
    Rotated textframe
    <TextFrame Self="u136" ParentStory="u124" ItemTransform="0 1 -1 0 320.3805483338268 -125.07900895050204">
                <Properties>
                    <PathGeometry>
                        <GeometryPathType PathOpen="false">
                            <PathPointArray>
                                <PathPointType Anchor="-101.72727272727272 -46.581818181818164" LeftDirection="-101.72727272727272 -46.581818181818164" RightDirection="-101.72727272727272 -46.581818181818164"/>
                                <PathPointType Anchor="-101.72727272727272 -0.3272727272727103" LeftDirection="-101.72727272727272 -0.3272727272727103" RightDirection="-101.72727272727272 -0.3272727272727103"/>
                                <PathPointType Anchor="115.9090909090909 -0.3272727272727103" LeftDirection="115.9090909090909 -0.3272727272727103" RightDirection="115.9090909090909 -0.3272727272727103"/>
                                <PathPointType Anchor="115.9090909090909 -46.581818181818164" LeftDirection="115.9090909090909 -46.581818181818164" RightDirection="115.9090909090909 -46.581818181818164"/>
                            </PathPointArray>
                        </GeometryPathType>
                    </PathGeometry>
                </Properties>        
    </TextFrame>
    When I converted the values of rotated textframe in to coordinates and drawn in a screen then  I am not getting the exact position where it drawn in the original.
    Can anyone help me to find out the cordinates of rotated textframe.
    Thanks in advance.

    It seems pretty straightforward to me.
    Your center point is (42.375 mm, 27.458 mm) and your box is 58.417 mm x 28.417mm.
    IDML defines the rectangle by its corners, not its center, so let's find the upper-left corner. Divide the width by two and subtract from the x, same for the height and the y. You get (13.665 mm, 13.2495 mm).
    That is in page coordinates relative to the upper-left corner of the page, we can see from your rulers.
    But IDML coordinates are spread-relative from the center of the spread. Your spread is a single page that is 85 mm x 55 mm.
    So if we translate your upper-left corner, it is (13.665, 13.2495) mm - (85/2, 55/2) => (29.3335 mm, 14.2505mm) in spread-relative coordinates.
    But IDML coordinates are in points, not in mm. So we convert (multiply by 2.835). And we get (83.150 pt, 40.395 pt).
    But that doesn't match up with your IDML file, which has  (-82.650 pt, -39.890pt).
    But look at the difference: (0.500 pt, 0.505 pt). That's really 1/2 point, because your box has a 1-pt border and that gets split evenly across all 4 sides. And there's 0.005 of round-off error, bceause floating point math sucks.
    Any questions?

Maybe you are looking for

  • Is it possible to update attributes in all tables in a multi entity view

    Hi I have a view based on 4 entities, all of which are a 3 of which are 1 to many relationship with the 4th. The 3 additional entities have 2 or 3 attributes, Id, name, and one entity has a foreign key relating to a different table which I do not car

  • I have finally finished my lightbox

    I finally got my LB working in IE i had to sacrifice the fade in effect and give IE its own code for many things. anyway 2 problems remain perhaps someone ca give suggestions 1) in the corner of the faded area the corners dont quite line up with the

  • Compile using command line

    Hi, I'm using JBuilder, and now I'm trying to compile the project in command line, using javac, or jar. I want to create JAR file, and it is very complicated and contains many files. Is there any way to exctract the command from JBuilder? Or from Ant

  • 30GB ipod does not play videos, it loads but does not streams...

    i have a 30gb 5gen ipod, ant it has a problem... it doesn't plays video. video clips i used were converted in itunes, so it had to fit the requirments. video loads ok, but when i try to play it it shows play sign in the left up corner, however nothig

  • Converting quicken to my mac

    I have quicken 2008 on my old toshiba and would like to upgrade and transfer to my mac book pro?  How do I do this or is there an apple equivalent?