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.

Similar Messages

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

  • 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.
    %

  • 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

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

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

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

  • Sine wave frequency error

    Hi! I'm pretty new to labview so any help will be appreciated!
    I'm trying to generate a 6-sine wave pulse using the attached generating and detecting vi. It all looks good, however, the frequency which I want the pulse to be generated ain't quite right no matter how I tweek it. For example, I keyed in the rate of generating pulse to be 1MHz in this case, but the detected signal is only 1 kHz (period = 0.001s). There should be no loss in this case. Other frequencies keyed in are also reduce by a thousand times. I think it is due to my Fs=1000 and #s=1000, because if i change my Fs to be 100 and #s=100, the detected frequency will be reduced by 100 times only. But if I reduce it, the resolution of my signal will be poor and I cant reduce it below 50 for a clear signal. Is there any way I can get the signal generated to be that which I typed in? Help!
    Thanks!
    Attachments:
    detect.jpg ‏48 KB
    generate.jpg ‏29 KB
    graph.jpg ‏118 KB

    Hi, I am using PXI-8331 with analog output PXI-6733 and analog input
    PXI-6133. I am generating voltage signals and collecting voltage
    signals as well.
    The problem I have is that when I
    intend to generate a 100kHz, 4 sine wave in a hanning window pulse, the
    received signal tells me that the signal generated was actually only
    100Hz (reduced by 1000 times) for Fs and #s of 1000, and it will be
    1000Hz (reduced by 100 times)  for Fs and #s of 100. What I hope to
    achieve is for the detected signal to show me that the actuated signal
    is indeed that which is keyed in. I am currently using DAQ assistant to
    control the frequency of my windowed sine wave. Is there any other way
    to go around doing it?
    On a side note, yes, I understand
    Nyquist theorem. I tried using 10kHz generating signal and 1MHz
    sampling frequency (100 times difference) for signal detection, but the
    results is exactly the same as that received using 10kHz sampling
    frequency and thus I believe there should be something I am not getting
    quite right about my signal generation since the frequency is always
    reduced by Fs times and I can't change its period.
     I have attached the vi I am using. Thanks a lot for your reply.
    Attachments:
    combining_testing2_6_2_testtest.vi ‏395 KB

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

  • Error #3115 Folio Builder (Mac)

    Sono Italiana. C'è qualcuno che può aiutarmi a capire cos'è l'errore [Error #3115] nell'istallazione di Digital Publishing Suite/Folio Builder? il Folio NON funziona, mentre l'Overlay Creator sì. Ho un Mac e InDD CS5.5

    Oops .. sorry
    Check this one .. http://forums.adobe.com/message/4265514#4265514
    -=-=-=-
    On Mac /Users/user name/Library/Preferences/ StageManager.<long_guid>/Local Store/
    Please delete following cache file/folders:
    *    #SharedObjects
    *    Dmp folder
    -=-=-=-

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

  • Iphone 4 errore sincronizzazione 1140

    Cos'è l'errore sincronizzazione 1140 che mi appare mentre cerco di sincronizzare l'iphone 4 con iTunes?

    Update: try updating to iPhoto 9.4.1. If it's not appearing in your Software Update yet, try updating using a .dmg installer downloaded from the following page on the Apple website:
    iPhoto 9.4.1
    From the release notes for the new version:
    What's New in Version 9.4.1
    Improves the reliability of syncing to iOS devices via iTunes
    Fixes an issue that could cause iPhoto to quit unexpectedly when using the Export command
    Addresses an issue that could cause iPhoto to quit unexpectedly when upgrading multiple books, cards, and calendars
    Resolves an issue with downloading and viewing photos synced from Facebook albums

  • Can't load service ejb

    Hi everybody:
    This error happens in our server in the night:
    [GC 482880K->402270K(1007616K), 0.0517355 secs]
    [GC 484190K->401323K(1007616K), 0.0495883 secs]
    [GC 483243K->401305K(1007616K), 0.0492152 secs]
    [GC 483225K->401760K(1007616K), 0.0501447 secs]
    [GC 483664K->401810K(1007616K), 0.0495283 secs]
    [GC 483718K->401693K(1007616K), 0.0474358 secs]
    [GC 483597K->401671K(1007616K), 0.0466509 secs]
    Element 342588564 disconnected.    Fri Jan 27 00:59:15 CST 2006
    Shutting down the J2EE Engine [Fri Jan 27 00:59:18 CST 2006]
    Stopping additional services.
    Shutting down service LogViewer
      Stopping: service logviewer ... done.
      Stopping: service javamail ... done.
      Stopping: service telnet ... done.
      Stopping: service appclient ... done.
      Stopping: service runtimeinfo ... done.
      Stopping: service PRTBridge ... done.
      Stopping: service pinger ... done.
      Stopping: service shell ... done.
      Stopping: service eisconnector ... done.
    [Dynamic-linking native method com.sap.mw.jco.rfc.MiddlewareRFC.nativeInitialize ... JNI]
    [Dynamic-linking native method com.sap.mw.jco.rfc.MiddlewareRFC.nativeSetTraceLevel ... JNI]
      Stopping: service rfcengine ... done.
      Stopping: service ejb ... done.
      Stopping: service dbpool ... done.
      Stopping: service ts ... done.
    [GC 483590K->401469K(1007616K), 0.0484396 secs]
      Stopping: service metamatrix ... done.
      Stopping: service jms ... done.
    ........Enterprise Portal is shutting down ........
    [Releasing Portal Component ] com.sap.portal.navigation.detailedtree.DetailedNavigationTree
    [Releasing Portal Component ] com.sap.portal.runtime.config.component.ConfigUI
    [Releasing Portal Component ] com.sap.netweaver.coll.appl.ui.rtc.RTCComponent
    [Releasing Portal Component ] com.sap.portal.appdesigner.contentcatalog.PersonalizedPageSearch
    And now I can't start the server service:
    [Dynamic-linking native method java.io.RandomAccessFile.readBytes ... JNI]
    [Dynamic-linking native method java.io.RandomAccessFile.writeBytes ... JNI]
    Loading: ServiceManager ...
    ID000539: Classload error; Can't load service ejb because referenced service eisconnector not found
    ID000538: Classload error; Can't load service deploy because an error in loading referenced service ejb is occured
    ID000541: Classload error; Can't load core service deploy
    [ServiceManager]: ID000541: Classload error; Can't load core service deploy
    Loading: ServiceManager returned false!
    Kernel not loaded. System halted.
    [Framework -> criticalShutdown] [Fri Jan 27 09:15:27 CST 2006] Kernel startup failed.
    [Dynamic-linking native method java.lang.Shutdown.halt ... JNI]
    Fri Jan 27 09:21:15 CST 2006
    [Dynamic-linking native method java.lang.StrictMath.sin ... JNI]
    [Dynamic-linking native method java.lang.StrictMath.cos ... JNI]
    [Dynamic-linking native method java.lang.Float.intBitsToFloat ... JNI]
    [Dynamic-linking nat
    Any Idea of what is happenning?
    Thanks in andvance
    Flavio Jasso S

    Let me take a shot:
    services have a heirarchy of dependency. When one of the base required services does not start, the rest wouldn't start.
    "Can't load service ejb because referenced service eisconnector not found"
    So you need this configured connector. if not remove its reference from the EJB configuration file. Else try testing it seperately.
    Regards,
    Kumar

Maybe you are looking for

  • Cannot download my 15 available downloads, error says store is temp unavail

    I reported the problem through iTunes around 12/5 and they replied once about 8 days ago with a standard boiler plate reply, telling me to do several things that I had already done. I wrote back with more details and got no reply, and then I wrote ba

  • How do i get windows to have enternet

    I have windows installed and the internet does not work. I have uninstalled and reinstalled it.

  • Can't copy project to external HD

    Hi-- I am trying to free up space on my daughter's iBook (G3). I read on support, that ideally you should be able to drag the starred movie project onto the external HD and copy it that way. I keep getting a warning that says, cannot copy "icon, beca

  • Constant re-authorization of purchased music

    When I open Itunes, i can play all my purchased music fine. But when I open IDVD or an IPhoto slide show that uses purchased music, it constantly asks to authorize the computer to play the song again. Its to the point where I cannot even open idvd wi

  • ASP VBScript , Remote_User server variable, and Access DB

    I need to recreate some ASP pages that were orginally created in MS FrontPage once upon a time. I have a table in an Access DB that contains the user's login ID. I need to pull the date the user completed a quiz at the end of a web training module. M