Hi again, I was working on another homework assignment and I got stuck trying to figure out why my program wasn't computing the right answer. The assignment was to basically write a program that computes the Sine function (as close as you possibly can) without using Math.sin(). I believe that my for loop in the original code is not doing the factorial for the right variable. I'm pretty sure the equation is right as well. I figured out the series needed to compute sin:
Sine = (-1.0^n)(x^(2n+1)) / (2n+1)!
Here's my original code:
/* This program is suppose to compute the Sine function without using Math.sin */ import java.io.*; public class HW5 { public static void main(String args[]) throws IOException { BufferedReader keybd = new BufferedReader(new InputStreamReader(System.in)); String s; double Rad, Sine; int MaxE, i; Rad = 0.0; System.out.println("Degrees (d)? or Radians (r)? Please enter (d) or (r): "); s = keybd.readLine(); s = s.toLowerCase(); s = s.trim(); if (s.equals("d")) { System.out.println("Enter a value (Degrees): "); Rad = Double.parseDouble(keybd.readLine()); Rad = (Math.PI * Rad) / 180; } else if (s.equals("r")) { System.out.println("Enter a value (Radians): "); Rad = Double.parseDouble(keybd.readLine()); } System.out.println("Enter the desired maximum exponent: "); MaxE = Integer.parseInt(keybd.readLine()); **************************************************************** i = (2 * MaxE) + 1; //This is where I think I messed and confused myself for (int a = 0; a <= MaxE; a++) { i = a * i; } Sine = ((Math.pow(-1.0,MaxE))*(Math.pow(Rad, i)) / i!); // I put the ! to indicate where I wanted the factorial to go System.out.println("The value of Sine is " + Sine); } }
My first problem was trying to figure out how to compute a factorial. I looked through the tutorials and found some code for recursive factorials but I couldn't get it to work. I ended up finding a code that I got to work but the problem is is that I'm not sure how I could incorporate it into my original code.
Factorial program:
import java.io.*; public class s { public static void main(String args[]) { try { BufferedReader object = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the number"); int a = Integer.parseInt(object.readLine()); int fact = 1; System.out.println("Factorial of " + a + ":"); for (int i = 1; i <= a; i++) { fact = fact * i; } System.out.println(fact); } catch (Exception e) {} } }
I apologize for this being so long but I'm not sure if my logic is right or not. Also, does java have a built in factorial method or did I have to make a loop for it? Any help is appreciated.