Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Trigonometry and Java

  1. #1
    Junior Member
    Join Date
    Sep 2012
    Posts
    2
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Trigonometry and Java

    Hello all,
    I am taking a class for introduction to programming and the choice language is Java. For the first assignment, the teacher wants us to learn to be creative with the tools he taught us. Here is the question:

    Write a program in Java that computes the trigonometric function sin(x) given by the
    series
    sin(x) = x – x^3/3! + x^5/5! – x^7/7! + ...
    The program should take as input a number from the command-line, and output the sine value of that number.

    I am not looking for an outright answer on these forums. I want to be able to complete that problem on my own. However, my mathematics are far behind me and furthermore, I learned them in french. I'd like indications on what I should do, mainly from a mathematical perpective. From there on, I can try to translate that to Java and deal with it's limitations.

    From what I understand, I can find multiple values for sin(x). I am trying to use the last formula from this link. I want to print the value of x if n=0 and then print it again with n++. However I have no idea of what to do with the "(2n+1)!" part of the equation. Furthermore, I'm not even sure if my method makes any sense.

    I'd be very thankful if somebody with a better understanding could give me some hints on what do do

    Guillaume
    Last edited by gu_cout; September 25th, 2012 at 03:48 PM.


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Trigonometry and Java

    Quote Originally Posted by gu_cout View Post
    Hello all,the teacher wants us to learn to be creative with the tools he taught us.
    What tools did you learn?



    Quote Originally Posted by gu_cout View Post
    I'd be very thankful if somebody with a better understanding could give me some hints on what do do
    Start out with a program that prints hello world. Compile, run, and test. Add code to accomplish a small part of your task. Compile, run, and test. Add another feature. etc

  3. #3
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: Trigonometry and Java

    The maths formula is nice and compact, but it isn't maybe the best way of thinking of the series from the computation point of view.

    Basically what you have to do is add the following together:

    x
    -x^3/3!
    x^5/5!
    -x^7/7!
    etc

    How many terms you add together is a fussy detail you can put off to start with. The first hint I'll give is that this is calling out for a loop. So if you want to add ten terms of the series, use a for loop going from 0 to less than 10. (Or, it might turn out that a while loop is better. Again this is a detail you can decide on later).

    The general "outline" of using a loop to evaluate a series is:

    int sum = 0;
    for(int i = 0; i < 100; i++) {
        int term = i * i;
        sum += term;
    }
        // prints 0^2 + 1^2 + 3^2 + ... + 99^2
    System.out.println(sum);

    sum is sometimes called an "accumulator".

    The other hint is to look at the structure of each term of the series. It is a fraction: that is it has a numerator and a denominator. (I don't know the French terms ... it has a "top" and a "bottom"!) As you go round and round the for loop, these update in a particularly simple way:

    int num = 0;
    int denom = 1;
    int sum;
    for(etc) {
            // what do we have to multiply num from the last round by
            // to get its value in the current round
        num *= ... 
            // same with denom
        denom *= ...
     
        // ...
    }

    Note I'm using sum+=something to mean sum=sum+something. The same with *=. You may or may not have seen this syntax.

  4. The Following User Says Thank You to pbrockway2 For This Useful Post:

    gu_cout (September 25th, 2012)

  5. #4
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Trigonometry and Java

    First of all, the exclamation mark (the '!') indicates the mathematical Factorial function. This is not part of the Java Math class, but it's not too hard to write your own. Even though it is an integer function, I would (probably) implement it with double precision floating point variables. Java integer variables overflow after 12 factorial. Java long variables overflow after 20 factorial. Double precision variables won't be exact above something like 18 factorial, but if you start small and multiply by successively larger values, results may very well be acceptable. At least it will go a long way farther before overflowing. (Maybe you won't have to go that far.)

    Here's the first paragraph from Factorial - Wikipedia

    In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example,

    5 ! = 5 times 4 times 3 times 2 times 1 = 120

    The value of 0! is 1, according to the convention for an empty product.


    To calculate n factorial, I would just make a loop with a product variable that starts at 1 and goes through the loop, multiplying by increasing term values each time through the loop. The loop terminates after it multiplies by n.

    Now...

    Here's how the stuff about the big Sigma pans out: The stuff below and above the Sigma symbol indicates that the function denoted sin(x) is "equal to" the sum of an infinite number of terms, starting at n = 0

    The stuff to the right of the big Sigma tells you how the terms are determined:

    The first term is for n = 0

    For n = 0, 2n+1 = 1.
    (-1) to the power n is (-1) to the power 0. That value is 1
    The numerator is x to the power (2n+1), which is x to the power 1. That value is 1.
    The denominator is (2n+1) factorial, which is 1 factorial. That value is 1.


    The next term is for n = 1, so 2n+1 = 3
    (-1) to the power n is (-1) to the power 1. That value is -1
    The numerator is x to the power (2n+1), which is x to the power 3
    The denominator is (2n+1) factorial, which is 3 factorial.

    The next term is for n = 2, so 2n+1 = 5 (See how it goes, as n = 0, 1, 2, ... we see that 2n+1 is the sequence of odd integers)
    (-1) to the power n is (-1) to the power 2. That value is 1
    The numerator is x to the power (2n+1), which is x to the power 5
    The denominator is (2n+1) factorial, which is 5 factorial.

    Etc.

    Bottom line: Mathematicians love stuff like that big Sigma notation, since it tells us exactly how to calculate each term instead of writing stuff like
    x - x^3/3! + x^5/5! - ...

    See? That "..." stuff (ellipsis) means "continue in the same manner," which assumes that we recognize the pattern so that we can get to the next term in a deterministic fashion. I don't know about you, but I actually prefer the big Sigma stuff for the definition. Then you can write out as many individual terms as you want. (I will say that it takes a little getting used to for some of us. At least it did for me.)

    Anyhow, given the mathematical definition, here's kind of a head-scratcher:

    How can you calculate the sum of an infinite number of terms on a computer (in a finite amount of time)? Think about it.

    Aha! That's an easy one: You can't. Therefore you will have to stop sooner or later.

    The Big Deal that you need to be able to figure out is: What is the error if you truncate the series after a particular number of terms?

    Well, this particular series has two mathematical properties that can help you make a decision. (Proofs are left as an exercise for math class.)

    The series converges for all finite values of x.
    The signs of successive terms alternate +, -, +, -

    Now, it "turns out that" for all series with these properties, the absolute value of the truncation error is less than or equal to the absolute value of the first neglected term. (Not true for series in general, but thankfully it's OK for this one.)

    Bottom line: If you are given an assignment to calculate the approximate value of the sum of an infinite number of terms, you should be given instructions about how many terms to use or, maybe a specification that defines the maximum allowable truncation error.

    Maybe this is enough to get you started?

    pbrockway2 has given some really good clues that allow you to arrive at values of successive terms by operating in simple ways on the most recent term, so you don't necessarily have to calculate powers of x and x factorial for each term. Results should be the same. (Maybe roundoff error considerations might favor one form over the other, but I don't think we are ready to get into that just yet, right?)



    Cheers!

    Z
    Last edited by Zaphod_b; September 25th, 2012 at 04:53 PM.

  6. The Following User Says Thank You to Zaphod_b For This Useful Post:

    gu_cout (September 25th, 2012)

  7. #5
    Junior Member
    Join Date
    Sep 2012
    Posts
    2
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Trigonometry and Java

    Thank you all very much for your help. Here's the source code I ended up with:
    /*  
      Filename: SineValueRadiants
      Author: Guillaume Couture
      Date: September 27, 2012
      Description: The program prints the sine value of a radiant input
    */
     
    public class SineValueRadiants {
     
      public static void main(String[] args) {
      double x = (Double.valueOf(args[0])).doubleValue(); 
      double term = 1;
      double n;
      double fact = 1; 
      double sinx;
     
     
        //Calculate the sinx with 17 terms
        for (n = 1, sinx = 0; term <= 17 ; n = n + 2, term++) {
          //Calculate factorial value of n
          fact = 1;
          for (double i=1; i<=n; i++) {
            fact = fact*i;
          }
          //Verify if the term is an odd number to apply the right term sign
          if (term%2 == 1){
          sinx = sinx + Math.pow(x,n)/fact;
          }
        else {
          sinx = sinx - (Math.pow(x,n)/fact); 
        }
      }
        System.out.println("the sine of "+x+" is : "+sinx);
    }
    }

    It took me a few hours of pulling my hair out to realize I had to set the factorial back to 1 before each loop.
    Last edited by gu_cout; September 28th, 2012 at 11:26 AM.

Similar Threads

  1. Trigonometry - Bearing
    By L8TON in forum Algorithms & Recursion
    Replies: 1
    Last Post: January 18th, 2012, 06:03 PM
  2. Geometry/Trigonometry Question
    By barrett777 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: December 30th, 2010, 06:48 AM