import java.util.*;
import java.math.*;
public class SinCos{
public static void main(String args[]){
Scanner kb=new Scanner(System.in);
System.out.println("Enter the angle for cosine: ");
double anglecos=kb.nextDouble();
System.out.println("Enter the number of expansions required:");
int n=kb.nextInt();
System.out.println("Enter the angle for sine:");
double anglesin=kb.nextDouble();
System.out.println("Enter the number of expansions required:");
int n2=kb.nextInt();
System.out.println("Cosine: "+workCos(anglecos,n));
System.out.println("Sine: " +workSin(anglesin,n2));
}
public static double workCos(double angle, int num){
double ans=0;
int times;
for(int k=0;k<=num;k++){
times=(2*k);
ans=(ans + ((Math.pow(-1,k)*Math.pow(angle,times))/(fact(times))));
}
return ans;
}
public static double workSin(double angle, int num){
double ans=(angle*Math.PI)/180;
int times;
for(int k=0;k<=num;k++){
times=(2*k)+1;
ans=(ans + ((Math.pow(-1,k)*Math.pow(angle,times))/(fact(times))));
System.out.println(ans);
}
return ans;
}
public static int fact(int num){
if(num==0||num==1){
return 1;
}
else{
return num* fact(num-1);
}
}
}
In this code above I'm trying to compute sine and cosine. However I'm
not getting correct results. It seems perfectly logical. To do this, I'm
using Taylor's series. can you tell me what's the problem with my
code?
Sadly 13! and above will overflow the int type in Java.
So any value of num above 12 in fact(int num) will give unexpected results.
One remedy is to use a long which gets you up to 19!, by which time the series ought to have converged adequately. Using a double will yield more terms, with any loss of precision being well within the accuracy of your series approach.
I think your formula is a bit off. Take a look here.
Try sin like this:
public static double workSin(double angle, int num){
double ans = 0;
for(int n = 1; n <= num; n++) {
ans += Math.pow(-1, n - 1) * Math.pow(angle, 2*n - 1) / fact(2*n - 1);
System.out.println(ans);
}
return ans;
}
and cos like this:
public static double workCos(double angle, int num) {
double ans = 1;
for(int n = 1; n < num; n++) {
ans += Math.pow(-1, n) * Math.pow(angle, 2*n) / fact(2*n);
System.out.println(ans);
}
return ans;
}
Related
Im Currently working on one of my excercises for university.
I have to calculate the cos(x) by using a taylor series. Im also just allowed to use Math.PI which is why i implemented my own pow, square and factorial methods. But im just getting an NaN as a result for -.5 while it should be 0.87
Below im putting the current state of my class.
class Cosinus{
private static double square(double x){
return x*x;
}
public static double pow(double basis, int exp){
if(exp == 0){
return 1;
}else{
return (square(pow(basis,exp/2))*(exp%2==1?basis:1));
}
}
public static int fac(int n){
int result = 1;
while (n > 1){
result *= n;
n -= 1;
}
return result;
}
public static void main(String[] args){
if(args.length != 1){
System.out.println("ERROR PLEASE ENTER A NUMBER");
}
else if(Double.parseDouble(args[0])>((Math.PI)*2) || Double.parseDouble(args[0]) < ((Math.PI)*-2)){
System.out.println("ERROR PLEASE ENTER A NUMBER BETWEEN 0 AND 2 PI ");
}
else {
double x = Double.parseDouble(args[0]);
if(x < 0) x *= -1;
double sum = 1;
for(int i=2; i<=20; i++){
sum -= (pow(x, (i*4))/fac(i*4))-(pow(x, (i*4+2))/fac(i*4+2));
}
System.out.println(sum);
}
}
}
Would be nice if someone could help me with this
Factorial(20) is 2e18 which is larger than an int can hold. If you change your fac method to use long instead it will give you the expected result:
public static long fac(int n) {
long result = 1;
while (n > 1) {
result *= n;
--n;
}
return result;
}
I know this is basis problem, but I just can't solve this, so I need your help..
I am trying to find the average of digits of the number(user input) by using While Loop, like for example, the average of digits of the number 789 is (7+8+9+)/3 = 8.
Could anyone help me with this..? Thank you so much.
import java.util.Scanner;
public class AVE
{
static int digits = 0;
static int average =0;
static int sum =0;
static int number;
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
System.out.println("what is your number?");
number = kb.nextInt();
avDigits();
System.out.println("The average is " + average);
}
public static void avDigits()
{
int num = number;
while (num > 0)
{
digits += 1;
sum += digits % 10;
num/=10;
}
average = (sum/digits);
}
}
Your issue is with the mod. You can rewrite the code as follows, Modification is done not only to correct the error but to make standardized. You need to change average to float or double.
import java.util.Scanner;
public class AVE {
public static void main(String[] args) {
int number;
float average = 0;
Scanner kb = new Scanner(System.in);
System.out.println("what is your number?");
number = kb.nextInt();
average = avDigits(number);
System.out.println("The average is " + average);
}
private static float avDigits(int number) {
int digits = 0;
float sum = 0.0F;
while (number > 0) {
digits += 1;
sum += number % 10;
number /= 10;
}
return (sum / digits);
}
}
You are taking mod of digits instead of num. Change the while loop as following:
while (num > 0)
{
digits += 1;
sum += num % 10; //<< Take mod of num here
num/=10;
}
import java.util.Scanner;
class AVE
{
static int digits = 0;
static float average =0;
static int sum =0;
static int number;
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
System.out.println("what is your number?");
number = kb.nextInt();
avDigits();
System.out.println("The average is " + average);
}
public static void avDigits()
{
int num = number;
while (num > 0)
{
digits += 1;
sum += num % 10; /*Do the modulo of num instead of digit. Since doing the modulo of num will give you the last digit*/
num/=10;
}
average = ((float)sum/digits); //average can be in decimal also
}
}
I found someone who had a similar problem (How to calculate the median of an array?), but I couldn't figure out how to incororate it in to my own code since I am rather new to java. Right now, my findmedian method is returning 0 instead of the actual median and I can't seem to figure it out. Thanks!
import java.util.Scanner;
import java.util.Arrays;
public class Original
{
public static void main(String[] args)
{
Scanner inputNumber = new Scanner(System.in);
Scanner dataItem = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.print("This stores a list of contirbutions to a charity drive.\n ");
System.out.print("How many contributors will be entered? ");
double contributors = inputNumber.nextDouble();
double contributions[ ] = new double[50];
double contributions_check[] = findData (contributors, contributions);
System.out.print("See if the contributions are correct. ");
// Displays the contributions, loop allows numbers to be displayed correctly
for (int count = 0; count < contributors; count++) {
System.out.print(contributions_check[count] + " ");
}
double median = findmedian(contributors,contributions_check);
System.out.print("\n The median contribution is: " + median);
}
public static double[] findData(double n, double[] contributions2)
{
Scanner dataItem = new Scanner(System.in);
// x must be 0 and x must be < than n
for (int x = 0; x < n; x++) {
System.out.print("Please enter the next contribution: ");
contributions2[x] = dataItem.nextDouble();
}
return contributions2;
}
public static double findmedian(double n, double data[])
{
Arrays.sort(data);
double median;
if (data.length % 2 == 0) {
median = ((double) data[data.length / 2] +
(double) data[data.length / 2 - 1]) / 2;
} else {
median = (double) data[data.length/2];
}
return median;
}
}
I think the issue is you are using data.length in findmedian, where you should be using n. data.length is always going to be 50, even if you only entered 5 items....
Use the number of contributors n to know the valid contributors in your array.
public static double findmedian(double n, double data[])
{
Arrays.sort(data);
double median;
if (data.length % 2 == 0) {
median = ((double) data[n / 2] +
(double) data[n / 2 - 1]) / 2;
} else {
median = (double) data[n/2];
}
return median;
}
This code is designed for summing up the digits of the number but it brings up
javac Root.java Root.java:17: error: '.class' expected
Who can explain what is the problem here. Also i want to make the same program using Arrays but i have problems with putting int in Array, if you have suggestions i am glade to here you.
import java.util.Scanner;
class Root {
public static int numRoot(int n, int sum){
while (n != 0) {
sum = sum + n % 10;
n = n / 10;
}
return sum;
}
public static void main(String[] args){
int sum = 0;
Scanner in = new Scanner(System.in);
System.out.print("Enter a number here");
int n = in.nextInt();
int root = numRoot(int sum, int n);
System.out.print("the sum of the digits off given num is " + root);
}
}
You have error here, Correct it.
int root = numRoot(int sum, int n); // this is wrong
Change it to
int root = numRoot(n,sum); // should use correct order of input parameters
This should be your method, you do not need to pass sum:
public static int numRoot(int n){
int sum=0;
while (n != 0) {
sum += n % 10;
n = n / 10;
}
return sum;
}
and you shall call it like this:
int root = numRoot(n);
How would I finish this program?
I know it is wrong where I have inputed the calculation into the code. What do I need to change to get the program to work the way the assignment asks (see image)? Also where would I loop it to recalculate if the user chooses to at the end?
package cosx;
import java.util.Scanner;
public class cosx2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the degree: ");
double degree = input.nextDouble();
double radian = getRadian(degree);
calculateCos(input, radian,degree);
}
public static double getRadian(double x) {
return x = (Math.PI/180)*x;
}
private static void calculateCos(Scanner std, double rad, double deg) {
System.out.print("How many terms do you want to calculate the cos: ");
int terms = std.nextInt();
double top;
double bottom;
double sum=0;
for(int i = 0; i<= terms; ++i){
top = Math.pow(-1, i);
bottom =1;
int repeat = 2*i+1;
for(int j = 1; j <= repeat; ++j){
bottom *= j;
}
if(i%2 == 0)
sum += (top/bottom);
else
sum -= (top/bottom);
}
System.out.printf("The sin (%.1f", deg);
System.out.printf(") is %.6f", sum);
}
}