Math.sin() problem

Hi!
I need calculating sin in java but i need it in degrees and java doing it in rads. Anybody knows what can i do?
Thanx!!!
Max

Maybe you should look through the API at that Math class. You're already using Math.sin() ... how could you have missed Math.toDegrees() and Math.toRadians() ???

Similar Messages

  • Cosine/Sine problems

    I was writing some code for a simple game, and at the moment the focus is getting the character to move. To "strafe" to the right, I have used the following method:
    public void moveRight() {
              double tempAngle = horizAngle - 90.0;
              location.setX(location.getX() + (Math.cos(tempAngle) * runSidewaySpeed));
              location.setY(location.getY() + (Math.sin(tempAngle) * runSidewaySpeed));
    }I used the following values for the first test:
    double horizAngle = 0.0
    double runSidewaySpeed = 2.0
    And I centered the Location on (0, 0), the origin. If you do the math, activating this method should change the location to (0, 2). It does not, however. Instead it moves the character in the correct Y direction, but not far enough, and in the negative direction of the X, which isn't supposed to move at all.
    I looked through the code, and I found the glitch. From what I've learned the Cosine of -90 (tempAngle's value) is 0. But when I use a System.out.println to check it, the program reveals that the cosine of -90 is -0.44807... Sine returned the same result.
    What am I doing wrong? Or if there really is a problem with the Math.sin() / Math.cos(), and if so, can someone suggest an alternative?
    EDIT: Never mind, I discovered my problem. The Cosine/Sine methods take radians, not degrees. The API is sort of deceiving.
    "Returns the trigonometric cosine of an angle."
    Message was edited by:
    Goron40

    EDIT: Never mind, I discovered my problem. The
    Cosine/Sine methods take radians, not degrees. The
    API is sort of deceiving.
    "Returns the trigonometric cosine of an angle."How is that decieving? This is what it says:
    cos
    public static double cos(double a)
        Returns the trigonometric cosine of an angle. Special cases:
            * If the argument is NaN or an infinity, then the result is NaN.
        The computed result must be within 1 ulp of the exact result. Results must be semi-monotonic.
        Parameters:
            a - an angle, in radians.
        Returns:
            the cosine of the argument.Seems pretty clear to me.

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

  • Acrobat Pro 6 Average Daily Production and Math.round problem

    Acrobat Pro 6 Average Daily Production and Math.round problem
    (Production.0) (154) (whole units) . (Production.1) (90) (fractional) / (divided by) 31 (days) results in (Average.0) (4)(whole units) . (Average.1) (10) (fractional) using :Math.round.� Noticed that 154 (whole units) . 85 through 99 (fractional) also show 4.10. (without Math.round : 5.00)
    Method:
    �Production.0� (whole units) . �Production .1� (fractional) / Days = (Average Daily Production) (�Average.0� (whole units) . (Average.1) (fractional)
    � Production.0 (value not calculated)�, � Production 1 (calculated) (event.value = util.printx("0099", (event.value)).substr(-2,2); � �Average.0 (value not calculate)�, and �Average.1 has following calculation:
    var punits = this.getField("Production.0");
    var pfrac = this.getField("Production.1");
    var average = 0.0;
    average = (punits.value + pfrac.value / 100) / this.getField("Days").value;
    this.getField("Average.0").value = average - average % 1;
    this.getField("Average.1").value = util.printx("0099", Math.round((average % 1 * 100))).substr(-2,2);
    �Math.round� appears to be a problem. Also, could you explain the purpose of �0099� . Anyway, why would 154.85 through 154.90 divided by 31 give 4,10. Also, their must be a better way, to find the average daily production. All you have to do is divided the production (whole. fractional) by the days, and display the average daily production as (whole. fractional). Any suggestions??

    There are a many loose ends in your question.
    First, I have never seen before a variable type called 'var'. Is it a java primitive or a class?
    Next, I cannot seem to find any class that has the printx method.
    When it comes to substr(-2,2), I get confused. First, I thought that it was a method of the String class, but I only got as far as substring(beginIndex, endIndex).
    If you really must break the production and average into pieces, try this:
    float average = (punits + pfrac/100) / days;
    int avg_units = (int)average;
    int avg_frac = (int)( (average - avg_units) * 100 );My guess is that util.printx("0099", x) formats x having two optional digits and two mandatory digits, showing 0-99 as 00-99, but allows to show numbers with three and four digits.
    154.85/31 = 4,9951612903225806451612903225806
    154.99/31= 4,9996774193548387096774193548387
    If you round the fraction of theese numbers multiplied by 100 ( = 99.51.. and 99.968...) you get 100, and this will be the output of printx. My guess for "4.10" is that substr(-2,2) returns the two first characters of the string, because the start index should not be zero. (According to java docs, substring throws an exception on a negative index, so what kind of class are you really using ??????)

  • Math.sin(Math.PI)

    It's a circular pre-loader. When I add the "SecondHalf" the preloader doesn't work and gives an error saying the script is causing the flash player to run slowly. How can I fix this?
    This code is in:  _root.first_mc._second_mc
    previewImage.onLoadProgress = function(targetMC, lBytes, tBytes) {
    //FirstHalf
    //This works only without "SecondHalf"
              percentDone=Math.round((lBytes / tBytes) * 100);
              _root.loaderPsnt_tx.percentDisplay.text = percentDone + "%";
    //SecondHalf
    //This is not working
          _root.mc_mask.clear();
          _root.mc_mask.beginFill(0xff0000, 100);
          _root.mc_mask.lineStyle(1, 0xff0000, 80);
          for (i=0; i>=c; i--) {
             x = Math.sin(Math.PI/90*i)*mask_ra;
             y = Math.cos(Math.PI/90*i)*mask_ra;
             _root.mc_mask.lineTo(x, y);
          _root.mc_mask.endFill();
          c = Math.round(percentDone * (-1.84));
    previewImage.onLoadStart = function(targetMC) {
              _root.loaderPsnt_tx._visible = _root.circle._visible = _root.mc_mask._visible = true;
              _root.circle.setMask(_root.mc_mask);
              var mask_ra:Number = (_root.circle._width / 1) * -1;
              var c:Number = 0;
              var percentDone:Number = 0;
    previewImage.onLoadComplete = function(targetMC) {
              _root.loaderPsnt_tx._visible = _root.circle._visible = _root.mc_mask._visible = false;

    mask_ra is undefined in onLoadProgress.
    use:
    var mask_ra:Number;
    previewImage.onLoadProgress = function(targetMC, lBytes, tBytes) {
    //FirstHalf
    //This works only without "SecondHalf"
              percentDone=Math.round((lBytes / tBytes) * 100);
              _root.loaderPsnt_tx.percentDisplay.text = percentDone + "%";
    //SecondHalf
    //This is not working
          _root.mc_mask.clear();
          _root.mc_mask.beginFill(0xff0000, 100);
          _root.mc_mask.lineStyle(1, 0xff0000, 80);
      c = Math.round(percentDone * (-1.84));
          for (i=0; i>=c; i--) {
             x = Math.sin(Math.PI/90*i)*mask_ra;
             y = Math.cos(Math.PI/90*i)*mask_ra;
             _root.mc_mask.lineTo(x, y);
          _root.mc_mask.endFill();
    previewImage.onLoadStart = function(targetMC) {
              _root.loaderPsnt_tx._visible = _root.circle._visible = _root.mc_mask._visible = true;
              _root.circle.setMask(_root.mc_mask);
             mask_ra = (_root.circle._width / 1) * -1;
              var c:Number = 0;
              var percentDone:Number = 0;
    previewImage.onLoadComplete = function(targetMC) {
              _root.loaderPsnt_tx._visible = _root.circle._visible = _root.mc_mask._visible = false;

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

  • He actualizado mi iphone 4 sin problemas, luego he conectado un iphone 3 y me ha borrado todos los datos del mismo, ¿como recupero los datos de este iphone?,¿donde puedo encontrar la copia de seguridad?

    He actualizado mi iphone 4 sin problemas, luego he conectado un iphone 3 y me ha borrado todos los datos del mismo, ¿como recupero los datos de este iphone?,¿donde puedo encontrar la copia de seguridad?

    Que tal Eric, Mira despues de una ardua busqueda se cual es el problema, lamentablemente es la MainBoard (La tarjeta principal del iPhone) pero te cuento que aun asi logre restaurarlo, tuve que dejarlo casi una semana en DFU MODE (Pantalla Negra) y se descargo por completo luego baje un programa llamado "redsn*w" la ultima version y en la parte de Extas> Even More> Restore pude restaurarlo. Cabe mencionar que la alegria solo me duro unos cuantos dias, porq de alli se me volvio a apagar asi que el mismo procedimiento, estuve buscando una tarjeta madre en tiendas online, pero basicamente es como comprar otro iphone!, Espero que te sirva de algo a mi me funciono, pero como sabras, algunos les funciona algunas cosas y a otros no, espero que si te funcione! Saludos

  • Mi imac se desconecta constantemente. sin embargo tengo un PC que sigue conectado sin problema alguno

    mi imac se desconecta constantemente. sin embargo tengo un PC que sigue conectado sin problema alguno

    tengo el imac recien adquirido... el 06 02... nunca a funcionado la conexion correctamente... soy novato con Mac... y lejos de ser un pro en informatica... pero me imagino que sera un problema de programacion o un fallo del ordenador...

  • Por qué en Premier CC no puedo oír bien el audio de un determinado clip que he importado a una secuencia (se desincroniza e incluso desaparece en ocasiones), si este mismo clip SI se oye sin problema cuando lo paso a través del reproductor?

    Por qué en Premier CC no puedo oír bien el audio de un clip que he importado a una secuencia (se desincroniza e incluso desaparece en ocasiones), si este mismo clip SI se oye sin problema cuando lo paso a través del reproductor?

    System requirements | Adobe Premiere Pro
    estos son los requerimientos, hay un alista de tarjetas compatibles y unas especificaciones para la terjeta de sonido, como no soy usuario de Win no te puedo ayudar más, debe haber, por supuesto, un lugar donde veas las especificaciones técnicas de todos tus componentes.
    igualmente en mis épocas de editor no he visto que se hagan trabajos profesionales en una portatil. en general eran tremendos fierros pesados, ruidosos y calentadores, esto puede haber cambiado y hoy día sea posible trabajar en una lap, no lo se...
    la diferencia dentre hacer play en el reproductor es que cuando metes el clip (no me dijiste el formato del clip) el audio ya no es como viene en el original. por ahi ya ese audio estaba al límite superior y al emparejarlo con los otros o filtrarlo o lo que sea que le hayas puesto en el Premiere, se termina de romper, lo raro es la desincronización.
    si tienes un poco de paciencia espera que alguien más sabio venga a ayudarte, y si no postea tu pregunta en el sitio en inglés que tiene un foro especial dedicado al premier donde va a haber unos expertos seguramente al día con el programa (eso sí vete con tus especificaciones encontradas) puedes traducir el mensaje aquí mismo con el traductor, y busca primero en el search las palabras clave par ver si otros usuarios tienen o tuvieron problemas parecidos
    https://forums.adobe.com/community/premiere

  • Using java.lang.Math.sin/tan/cos  to make an arc - very simple

    hi all,
    i'm trying to dynamically create an set of numbers in an arch pattern -- going left to right (counter clockwise) --- from 0 degrees to 180 degrees. -- similar to an upside down U
    Any ideas on how i would do a simple loop to put the number 1 in a semicircle.
    I'm guessing that it might look like this
    while(x < 181)
    g.drawString(Integer.toString(x) , java.lang.Math.sin(..), java.lang.Math.cos(...) )
    how may I ask does that work again ?
    s

    The coordinates of the unit circle are given by
    x = cos(t)
    y = sin(t)
    where 0 < t <= 2pi
    You'll want to scale and translate that... Here's a code fragment; play with it a little:for (double t=Math.PI/2; t < 2*Math.PI, t += .05) {
        double x = 100*Math.cos(t) + 100;
        double y = 100*Math.sin(t) + 100;
        g.drawLine((int) x, (int) y, (int) x, (int) y);
    }

  • HELP!!!  math.random() problem

    Hello,
    I was wondering if anyone can help me with a problem I'm
    running into using the math.random(). I'm using Flash CS3 and
    created a very simple script to select random frames in a simple
    movie. It works as expected in the CS3 environment and in Safari
    but it doesn't work correctly in Firefox or in the DotNetNuke
    module I am using. Here is the code:
    i = Math.ceil(Math.random() * 3);
    gotoAndPlay("Image"+i);
    I would appreciate any help you can provide.

    Remember that Math.random() function returns a positive double value between 0.0 and 1.0. For a better definition you can refer to the Math class in the API.
    Since this is an assignment, I am not going to give you the code but I'll just tell you how you should be going about solving this.
    Now you have two limits right? What you can do is, multiply the smaller of the two numbers (I guess in your case its going to be the top) with the random number generated by the Math.random() function. Just add a check to see if this result is lesser than the maximum limit. If yes, then go ahead and add that number to the array. If not, just repeat the same thing.
    I hope you got the idea. If you still have problems, please let me know.
    Plutaurian

  • DrawOval( ) and Math.tan( ) problem

    Hello,
    I want to make a very simple animation: a circle moves with a 30 degree angle over the screen.
    Now my problem:
    When I calculate the new x and y coordinates for the circle I use the "Math.tan( )" method. But when I want to use those coordinates in the drawOval( ) method they should be INTEGERS. But then they will be rounded numbers and nothing will happen. (A horizontal animation will follow, because of the rounding of the numbers...). Can DOUBLES be used in a way in those draw methods? (So there won't be any loss of precision.)
    Thanks in advance...

    This is my source:
    import java.awt.*;
    import java.applet.*;
    public class Demo extends Applet
    public void paint(Graphics g)
    double x=10,y=300;
    for (int xadjust = 1;xadjust < 300;xadjust++)
    // a 45 degree angle
    x = x + xadjust;
    y = y - ((Math.tan((1/4)*Math.PI)) * x); // calculate new y coordinate
    g.drawOval( (int)x,(int)y,15,15);
    }

  • Mi iMac es versión 10.6.8, procesador Intel Core Duo. Puede soportar iCloud sin problemas?

    Mi iMac es versión 10.6.8, procesador Intel Core Duo. Puede soportar iCloud?

    Hola, Sonia.
    Acabo de hacer una búsqueda en los foros en inglés y encuentro sólo un tema referido a tu problema, el que sólo tiene tres mensajes, incluyendo la consulta. Lamento decirte que no hay solución publicada, salvo las sugerencias de "instalar todo de nuevo", e "intentar instalar Acrobat, no desde el CD, sino que de un archivo bajado del sitio Adobe". Esta última fue descartada por el que presentó el problema porque ha usado el CD con éxito en otros Macs, tal como tú.
    Sin experiencia directa, ya que no tengo la CS, yo te sugeriría lo siguiente. Corre la Utilidad de Discos partiendo desde el CD original de tu OS X. pasa un par de veces el Reparar Disco, y luego Reparar los Permisos del Disco. Intenta de nuevo la instalación y, tan pronto como termines, corre nuevamente ka Utilidad de Discos, pero sin reiniciar el computador (esta vez puedes usar la copia que está en tu disco duro); y pasa Reparar los Permisos del Disco. Te lo digo porque he leído en muchas partes que es buena práctica hacer esto cada vez que se instala software.
    Suerte.

  • Instalar cuenta correo gmail sin problemas

    Buenos dias.
    Al tratar de añadir una cuenta gmail a mi mac book pro, me aparece un error al iniciar la instalacion, relacionado con el usuario y el password. Lo he revisado mil veces y son los correctos. Sin embargo sigue saliendo error.
    Que debo hacer?
    Gracias

    Hola, tengo el mismo problema que tú con una cuenta de gmail. Quería saber si finalmente has conseguido solucionarlo. Yo de momento lo único que he conseguido es recibir el correo reenviándolo a otra cuenta que sí me funciona. Un saludo

  • Math type problem in ms office (mac edition)

    Dear Apple Solver,
    The above mentioned are typed in math type in ms office ( windows edition).
    But after it has been opened in ms office ( mac edition ) in iMac ,
    the arrows are showing  like letter r
    and caps as dollars.( vector symbols)
    the symbol since as Q
    I need help from concerned developers.
    Regards
    SRINIVASAN N

    Hi,
    Yes, I'm having the same difficulty when installing FM Web
    Studio by FMWebSchool.com. I get the [empty] "Document type could
    not be added" error 33 times on application launch. I see no
    templates, no dynamic page creation options.
    PS. Edited to note I'm on MacOS 10.4.10, PowerPC, DW MX2004
    quote:
    Originally posted by:
    mpjx
    Hi all,
    I run DW MX2004 under OS X 10.4.10 on a Mac. I'm having
    trouble installing the Rubyweaver 2.0 extension (available from
    http://rubyweaver.gilluminate.com/)
    which should add ruby and rails functionality to DW. According to
    Extension Manager it is installed fine but when I try to use DW I
    get the following problems:
    1. On startup DW throws up a warning message:
    quote:
    The Document Type "" will not be added because it uses a file
    extension that is already associated with a prior document type.
    This message appears three times, I assume for
    three different document types.
    2. Rails, YML and SQL options are not present in the New
    Document window options (they should be).
    3. Preferences > Code Format > Tag Library Editor
    displays an option called 'Rails' - even when the checkbox is
    ticked, HTML colouring is not present in .rhtml files.
    I contacted the developer about these issues, he assured me
    that the extension was developed for and tested on both Windows and
    OS X platforms, and that nobody else had reported any problems. He
    suggested it must be a problem specific to my system.
    So, here's my question: has any one else experienced problems
    installing either this or another extension in DW MX2004 on a Mac
    and does anyone have a solution/work around.
    Thanks in advance for any help.

Maybe you are looking for