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

Similar Messages

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

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

  • How to graph sin and cos function on grapher?

    Hello,
    I am needing to graph this function on grapher, but can't (obviously, it's without the questinon mark). 
    All I get is this and no graph. :
    Can anybody tell me how to get the actual sin wave on the graph?
    Thanks!

    Here's how to animate a point along a graph. In this screenshot, we have the first function show the expected sine curve. The second function is a pair of values, defining x and y each as functions of "n" and then plotting the pair. Since x and y in this definition takes on one value at a time (and no range), you get a point. To animate the graph, you define "n" as a separate function (create a new function, delete the "y=" and replace with "n="). To make this a smooth evaluation of all points, click "n" to give it a value, and then press Option-Command-A to invoke "animation". You can then click the icon with checkmarks and two lines (to the far right seen here), and set the range for "n" along with subdivisions, or continuous values. You can then drag the slider to change the value for n, enter a specific value in the value box, or click the play button to animate back and forth.
    Note that in this screen shot, to in part answer the original poster's question, I've defined "f(x)" as the function "sin(x)" and then to display the function, since grapher plots y as a function of x, I've set y=f(x) so this behavior can be drawn. Its redundant, but allows for the management of functions in some ways that might be useful. For instance, you could do a set of functions such as the following:
    f(x)=x
    g(x)=x^2
    h(x)=x^3
    ...and then plot them all with y={f(x),g(x),h(x)}.
    In this instance, since the graphs are all increased powers of x, you can follow this trend by plotting over a set of values:
    set={1,2,3,4,5}
    f(x)=x^set
    This will plot x^1, x^2, x^3, x^4, x^5, etc...and you can also throw an "n" value in the set, then animate it, so some of the functions remain static while others are animated by the value of "n".
    ....the possibilities are vast.

  • Sine square function in formula node

    Hello
    I need to generate a function
    I = Iz * sin^2(B)
    where B = (pi/2)*(V/70)
    Iz = 0, 0.1, 0.2, 0.3 ... 1.0
    V = 1,2,3 ,4...135
    I tried to do thi sin formula node. but cud not get it.
    See attchment.
    Nghtcwrlr
    ********************Kudos are alwayzz Welcome !! ******************
    Attachments:
    Sine square in formulanode.vi ‏18 KB

    This will not work. B has 105 elements, and IZ has only 10. B and IZ must have the same numers of elements. And you should perhaps use a for loop not a formula node
    Besides which, my opinion is that Express VIs Carthage must be destroyed deleted
    (Sorry no Labview "brag list" so far)

  • Sin(wt) function in formula node

    How to create a function in formula node and plot it for Vo vs t
    V = Vo * sin(wt)
    with frequency = 50Hz
    Vo = -350 to 350
    Nghtcwrlr
    ********************Kudos are alwayzz Welcome !! ******************

    Why a formula node? Just use plain LabVIEW!!!
    Your specifications seem odd and incomplete. What is the range of t you want? "Vo vs t" only makes sense if V=constant unless you want a 3D or intensity graph: V(Vo, t).
    Please clarify!
    LabVIEW Champion . Do more with less code and in less time .

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

  • Coordinate Plane?

    Hello!
    I am trying to graph Sin & Cos functions using numbers. So far, all has gone smoothly. I have used a scatter plot with curved connections to connect the points.
    However, I have one (mostly ascetic) issue. When the graph appears the is no clearly indicated X and Y axis. For example, where 0 lies on the y-axis, a bolded line would usually take place of the thinner lines which otherwise carry the graph (and likewise on the x-axis). Is there any setting which would force the graph to clearly discern the X and Y axis?
    Thanks

    Correction: The first Numbers version had a Scatter Chart option, but it was of limited utility because it had no option to connect the data points with lines. This was such a source of dissatisfaction to the users that I guess subconsciously I see Numbers 09 as giving real life to the Scatter Chart. The point I was trying to make is that Numbers is on the steep part of the growth curve and we should be kind to the developers as they incorporate feedback to improve the product in stages.
    Jerry

  • 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

  • Including native database functions in partnerlink

    Is there a way to include native Oracle database functions (such as NVL) in the definition of a partnerlink based on a database adapter?

    Hi there,
    right now we do not support functions when visually creating the where clause in the dbadapter wizard.
    But there is a way to specify raw sql for the select outside the wizard.
    Please see the tutorial:
    integration/orabpel/samples/tutorials/122.DBAdapter/PureSQLSelect
    Thanks
    Steve

  • Trig etc functions on fractions?

    Fraction.java with trig methods?
    I've been playing with geospatial stuff for a while now, and I've been striking a lot of problems with the inherent inaccuracies of floating point number representations, especially in complex-calculated values.
    Here's a simple but pertinent example:
    class TheSumOfSevenSevethsIsNotOne
      public static void main(String[] args) {
        double f = 1.0/7.0;
        double sum = 0.0;
        for (int i=0; i<7; i++) {
          sum += f;
        System.out.println("sum = "+sum);
    // OUTPUT:
    // sum = 0.9999999999999998
    // not 1 as you might expectThe numbers I'm storing are latitudes and longitudes in degrees, so the max_value is just 360, but the requirement is that lat/lon must be accurate to 9 decimal places, which equates to about +/- 0.6 millimetres, which is (apparently) close enough to be regarded as "millimetre accuracy" by cartographers, even though total ambiguity is 1.2 mm.
    So three digits, plus six digits, is only nine digits, right?... and the humble int can store a tad more than 9 digits...
                                     123.123 456
    Integer.MAX_VALUE = (2^31)-1 = 2,147,483,647So I got to thinking... How would it be if I stored all lat/lons in the database as integers (multiplied by a million)? and did all my calculations rounded (not truncated) to the nearest 1. I could even save a few hundred million bytes that way... But that still leaves the same ole ambiguity around the actual calculations, many of which involve division ;-(.
    So I got to thinking maybe I could use fractions? How would a Fraction.java look?
    I googled around and found some great stuff, including:<ul>
    <li>[Diane Kramers Fraction.java|http://aleph0.clarku.edu/~djoyce/cs101/Resources/Fraction.java]
    <li>[Working with Fractions in Java|http://www.merriampark.com/fractions.htm] (includes BigFraction.java - very handy)
    <li>[Doug Leas Fraction.java|http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/misc/Fraction.java]
    </ul>
    But I haven't found anything which implements the basic trigonometry functions like sin, cos, tan, cot (and whatever else)... but [Daves Short Trig Course|http://www.clarku.edu/~djoyce/trig/] might give me the understanding required to do so... nor does any existing Fraction.java (which I've found so far) implement handy things like x^y, log, modulo (and whatever else) ... and not being a mathematician myself, I'm not overly eager to implement them... I'd never be sure I'd done the job properly.
    Please is anyone aware of any such implementations, even partial ones? Or could someone perhaps be persuaded to do part(s) of it just for the challenge?
    Cheers all. Keith.

    Sir Turing Pest,
    I do geospatial stuff amost exclusively and I dont understand this post.
    Why not just use doubles? The "error" you're seeing is so trivial.
    Put into perspective, if you were positioning something from the
    Sun to Pluto you'd be off by half a millimeter.
    How do you figure that you only need 9 digits?
    ignore 360 degrees. the circumference of the earth is 41k km and you need
    accuracy to .6 mm = 11 places
    (40 075.02 kilometers) / (.5 millimeters) = 80,150,040,000I didn't figure it, our local GIS expert did, based mainly on the size of an integer,
    When I do the math I get to 9 decimal places == about 1.11 mm, and that's allways rounded (not truncated) to 9 decimal places which I think means our points are accurate to plus or minus about 0.6 mm.... but I'm just a humble computer programmer, NOT a mathemetician or a geospatial expert.
    We're storing lat/lon to 9 decimal places... So 1 is 1 degree.
                   40,075.160000000     kilometers     circumference of the earth
    equals     40,075,160.000000000     meters        circumference of the earth
    equals        111,319.888888889     meters        meters per degree at the equator
    equals              0.000000001     degrees         storage accurracy
    equals              0.000111320     meters         
    equals              1.113198889     millemeters     storage accurracy in millimeters
    So sure you established that aggregate double addition comes out "wrong".
    Then dont do it, lol. Dont waste your time trying to invent new number
    storage. Just try to write your algorithms so you don't do aggregate addition as much.We try not to aggregate calculated values... but there are certain algorithms, like the reverse/mercator transforms where it's unavoidable... So opportunities for improvement is this area a likely to be NOT very cost effective, ie: bigger than Ben Hur, harder than a bulls azz, and uglier than an extreme closeup of my scotum... My main concern has been (rightly or wrongly) the inherent inaccuracy in our storage of numbers.... thinking that improvements in this area just might be cost-effective, and therefore doable.
    Iterestingly... we had a tree-clearing case kicked out of court recenctly because we couldn't define the boundaries of the national park in question to the satisfaction of the court... a "satisfaction level" which was based on our own "millimeter accuracy" definition of the required accuracy of survey data, which is based on international standards for GIS. ie: It's a bit of sore spot around the office at the moment, and I'm trying to do some bluddy thing about it... I'm just at a bit of a loss as to exactly what, without throwing literally millions of dollars at the problem to upgrade ALL our systems to 11 decimal places (or better). I'm in stress city.
    Cheers. Keith.

Maybe you are looking for

  • Xml file not displaying.

    Hello all, Pls i am trying to work on an example that displays some pics in form of slide show. Everything worked fine till i got to a point of displaying the content of an xml file. I tried all i could but things did not work out. someone pls help,

  • Using Clipmate to copy and paste between projects

    Thanks to Robert Johnston for the inspiration (and perspiration) for this method for copying and pasting between PE projects. One residual side effect of the method is that the audio and video of the copied clips will be unlinked. The renaming folder

  • Installing LR4 Beta but still keep LR3.5

    Hi LR people just a quick question (maybe dumb question)... Can I install the LR4 Beta and still keep my LR3.5? I presume that I just install it in a different folder in my Applications? Did I get that right? Oh I am running a MAC Pro. Thanks everyon

  • Memory Leak in 8.1 sp5

    Has anyone experienced a memory leak when a webservice (jws) returns a large string (5-15 Meg). The string itself is a XML. When the webservice is called numerous times it eventually runs out of memory.

  • JDEVELOPER  IDE SUCKS

    i only wish oracle corp is on the way to develop an IDE like the studio creator which uses simple style sheet concepts. I WASTE MOST OF THE TIME TO DEVELOP THE PRESENTATION LAYER THAN TO CONCENTRATE ON MY EXPERTISE(Business logic). I AM REALLY DISAPP