Skip to content

Instantly share code, notes, and snippets.

@bytecodeman bytecodeman/SineApp.java Secret
Last active Nov 4, 2019

Embed
What would you like to do?
CSC-111 Sin Calculation Prototype Code
/*
* Name: Tony Silvestri
* Date: 11/4/2019
* Course Number: CSC-111
* Course Name: Intro to Java
* Problem Number: HW7
* Email: silvestri@stcc.edu
* Description: HW7 Calculate Sine Function Using Series
*/
import java.util.Scanner;
public class SineApplication {
private final static String TITLE = "Sine Application";
private final static String CONTINUE_PROMPT = "Do this again? [y/N] ";
// **********************************************
// Put as many methods you need here
private static double power(double x, int exp) {
double result;
result = 1.0;
for (int i = 1; i <= exp; i++)
result *= x;
return result;
}
private static double factorial(int n) {
double result = 1.0;
for (int i = 1; i <= n; i++)
result *= i;
return result;
}
private static double sin(double x, int noOfTerms) {
double xinRads = x * Math.PI / 180.0;
double sum = 0.0;
int n = 1;
for (int i = 0; i < noOfTerms; i++) {
double num = power(xinRads, n);
double den = factorial(n);
double term = num / den;
int sign = i % 2 == 0 ? 1 : -1;
sum += sign * term;
n += 2;
}
return sum;
}
private static void outputResults(double x, double ans, int noOfTerms) {
System.out.printf("Number of Terms: %d\n", noOfTerms);
System.out.printf("Calculated sin(%f) = %.6f\n", x, ans);
System.out.printf("Real Math sin(%f) = %.6f\n", x, Math.sin(Math.toRadians(x)));
System.out.printf("Difference = %.6f\n", Math.sin(Math.toRadians(x)) - ans);
}
// **********************************************
// Start your logic coding in the process method
private static void process(Scanner sc, String args[]) {
System.out.print("Enter x in degrees: ");
double x = sc.nextDouble();
System.out.print("Number of Terms: ");
int noOfTerms = sc.nextInt();
sc.nextLine();
double ans = sin(x, noOfTerms);
outputResults(x, ans, noOfTerms);
}
// **********************************************
// Do not change the doThisAgain method
private static boolean doThisAgain(Scanner sc, String prompt) {
System.out.print(prompt);
String doOver = sc.nextLine();
return doOver.trim().equalsIgnoreCase("Y");
}
// **********************************************
// Do not change the main method
public static void main(String args[]) {
System.out.println("Welcome to " + TITLE);
Scanner sc = new Scanner(System.in);
do {
process(sc, args);
} while (doThisAgain(sc, CONTINUE_PROMPT));
sc.close();
System.out.println("Thank you for using " + TITLE);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.