cos(x) program confusion with function input - java

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);
}
}

Related

BigInteger Java How To Recreate A Formula

I tried to recreate this formula i am sure it's correct but the problem it gives me infinity and i need your help to transform it to BigInteger please help if possible
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner Input = new Scanner(System.in);
double X = Input.nextDouble();
double Y = Input.nextDouble();
double Ans = 0;
for (int I = 1; I <= 20; I++) {
for (int J = 1; J <= 20; J++) {
Ans += Math.log10(1 + Math.exp(Math.pow(-1, I + J) * (((Math.pow(I, 2) * X)) + (Math.pow(J, 2)) * Y)));
}
}
System.out.println(Ans);
}
}

Computing sine and cosine

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;
}

Calculating Average and Standard Deviation using do while loop

I am trying to write a program which asks the user for a series of positive values and computes the mean and standard deviation of those values having the input stop when the user enters -1. I seem to have the average part down however. I can't seem to get the standard deviation.
So far this is what I have.
import java.util.Scanner;
public class HW0402
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double x;
double sum = 0;
double average = 0;
double dev = 0;
double var = 0;
double sqrx = 0;
int n = 0;
do
{
System.out.println("Enter positive values, enter -1 to end");
x = input.nextInt();
if (x == -1)
{
break;
}
sum += x;
n++;
average = sum / n;
sqrx += Math.pow(x-average,2);
var = sqrx / (n-1);
dev = Math.sqrt(var);
} while (x != -1);
System.out.println("Average: " + average);
System.out.println("Deviation: " + dev);
}
}
I seem to get odd results such as decimals when simply calculating sqrx += x- average
I'm new to java and haven't leaned alternatives to this problem, I would love it if someone pointed me in the right direction on what I should do, or explain what I did wrong.
Apologies ahead of time for any novice mistakes I made.
int n = 0;
int K = 0;
double Sum = 0;
double Sum_sqr = 0;
do {
System.out.println("Enter positive values, enter -1 to end");
x = input.nextInt();
if (x == -1)
{
break;
}
if ( n == 0 ) K = x;
n++;
Sum += (x - K);
Sum_sqr += (x - K) * (x - K);
} while (x != -1);
double mean = K + Sum / n;
double varPop = (Sum_sqr - (Sum*Sum)/n) / (n);
double varSample = (Sum_sqr - (Sum*Sum)/n) / (n-1);
double devPop = Math.sqrt(varPop);
double devSample = Math.sqrt(varSample);
Reference Wikipedia: Computing Shifted Data. Also, Population or Sample, makes a difference.

How to sum powers of 2 with while loop

I need to calculate the sum of 2^0+2^1+2^2+...+2^n, where n is a number entered by the user. The main problem is that I don't know how to use the while loop to sum the different result of 2^n up.
Here is what I've tried:
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
while(power <= i) {
Math.pow(number, i);
sum = sum + Math.pow(number, i);
i = i + 1;
}
int result = (int)Math.pow(number, i);
System.out.println("The sum is: " + result);
}
}
Only you have to do is:
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
double sum = Math.pow(2,power+ 1 ) - 1;
System.out.println("The sum is: " + sum);
}
}
In this link explains the math expresion
All fine, just a few changes.
Change the parts code to
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
/*Remove this --------> while(power <= i) {*/
while (i <= power) {//it should be this
/*Remove this -------> Math.pow(number, i);*/
sum = sum + Math.pow(number, i);
i = i + 1;
}
System.out.println("The sum is: " + sum);
Your conditional is backwards, it should read:
while (i <= power)
You compute the sum of powers, then completely ignore it, just printing out the result of 2^i. you should be printing out sum, something like:
while (i <= power) {
sum += Math.pow(number, i);
i++;
}
System.out.println("The sum is: " + sum);
For style points this won't handle a negative power, so you'll need to test for that.
Dont understand why do you want to loop in this case. You can do it like :
System.out.println("The sum is: "+(Math.pow(2, power+1)-1 ));
But if you really want to use loop try this :
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
while(i<=power) {
sum = sum + Math.pow(number, i);
i = i + 1;
}
int result = (int)Math.pow(number, i);
System.out.println("The sum is: " + sum);
Here is a solution with comments to explain the logic. While loops need some kind of variable to control the number of iterations. That variable of course needs to be updated somewhere inside the loop.
You can compute the sum of the powers with the Math.pow() function, obviously. No import statement is needed to use it. I hope this helps. Good luck.
/* Scanner and variable to get and hold user input */
Scanner scan = new Scanner( System.in );
int userInput = 0;
/* Variable to hold the sum, initialized to 0.0 */
double sum = 0.0;
/* Prompt the user, and obtain the reply */
System.out.print( "Enter the exponent: ");
userInput = scan.nextInt();
/* The while loop and it's initialized counter */
int counter = 0;
while( counter <= userInput ){
/* Add each power to sum using Math.pow() */
sum = sum + Math.pow( 2, counter );
/* Watch the output as the loop runs */
System.out.println( "Sum: " + sum );
counter++; // Increment counter, so the loop exits properly
} // End while loop
public class SumofSquare {
public static void main(String[] args) {
// TODO Auto-generated method stub
String c = "123";
char d[] = c.toCharArray();
int a[] = new int[d.length + 1];
for (int i = 0; i < d.length; i++)
a[i] = d[i] - 48;
int r = 0;
for (int i = 0; i < c.length(); i++)
r = r + (int) Math.pow(a[i], a[i + 1]);
System.out.println(r);
}
}
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
int power=Integer.parseInt(reader.nextLine());
int number=2;
int i=0;
int result=0;
while (power>=i) {
result += (int)Math.pow(number, i);
i++;
}
System.out.println("The result is "+result);
}
}
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
double power=Double.parseDouble(reader.nextLine());
int number=2;
int i=0;
double sum=0;
while (power>=i) {
sum=sum+Math.pow(number, i);
i++;
}
System.out.println("The sum is "+sum);
}

Adding last average value

I'm having trouble adding the last number of the loop that I have. I don't have any ideas how to include the last number and then add it to the double variable and then divide it to make the average. I would use my IDE to solve the problem but the input has to be approximately 1000 trials in order to be accurate. You can plainly see that 10 trials of 3.0 or higher does not equal approximately 2.8. I just need to have the missing trial added and then calculated into the average.
Code:
import java.util.*;
public class CalculatePI2
{
public static boolean ifitisInside (double xPosion, double yPosion)
{
double distance = Math.sqrt((xPosion * xPosion) + (yPosion * yPosion));
return (distance < 1.0);
}
public static double calculatePI (int numThrows)
{
Random randomGen = new Random();
int hits = 0;
double PI = 0;
double Alpha=0;
double average= 0;
for( int m=0; m<10; m++)
{
Alpha=+PI;
average= m/Alpha;
if(m>=0)
{
hits=0;
PI=0;
for (int i = 0; i <= numThrows; i++)
{
double xPosion = (randomGen.nextDouble()) * 2 - 1.0;
double yPosion = (randomGen.nextDouble()) * 2 - 1.0;
if (ifitisInside(xPosion, yPosion))
{
hits++;
double dthrows = numThrows;
PI =+ (4.0 * (hits/dthrows));
}
}
System.out.println("Trial["+m+"]: ="+ PI);
}
}
System.out.println("Estimate:"+average);
return PI;
}
public static void main (String[] args)
{
Scanner pie = new Scanner (System.in);
System.out.println("This program approximates PI using the Monte Carlo method. By simulating throwing darts at a dartboard. ");
System.out.print("Please enter number of throws: ");
int numThrows = pie.nextInt();
double PI = calculatePI(numThrows);
}
}
Just take the average computation out of the inner loop. Also, the loop invariant is from 0 to < numthrows, not <= numthrows. Also, your initialization of the variables needs to happen for each of your 10 trials, so it needs to be moved inside the loop.
double sumPiOverMTrials = 0;
for( int m=0; m<10; m++)
{
double hits = 0;
for (int i = 0; i < numThrows; i++) {
double xPosition = (randomGen.nextDouble()) * 2 - 1.0;
double yPosition = (randomGen.nextDouble()) * 2 - 1.0;
if (ifitisInside(xPosition, yPosition))
{
hits++;
}
}
double pi = 4.0 * hits/numthrows;
System.out.println("Trial["+m+"]: ="+ pi);
sumPiOverMTrials += pi;
}
System.out.println("Average over "+m+" trials ="+ sumPiOverMTrials/10);
I think you can solve this just by rearranging your code:
public static double calculatePI (int numThrows)
{
Random randomGen = new Random();
int hits = 0;
double PI = 0;
double Alpha=0;
double average= 0;
for( int m=0; m<10; m++)
{
for (int i = 0; i <= numThrows; i++)
{
double xPosion = (randomGen.nextDouble()) * 2 - 1.0;
double yPosion = (randomGen.nextDouble()) * 2 - 1.0;
if (ifitisInside(xPosion, yPosion))
{
hits++;
double dthrows = numThrows;
PI += (4.0 * (hits/dthrows)); // NOTE: += not =+
}
}
Alpha+=PI; // NOTE += not =+
average= m/Alpha;
if(m>=0)
{
hits=0;
PI=0;
}
System.out.println("Trial["+m+"]: ="+ PI);
}
}
This way the average is calculated after each trial rather than before. Also, I don't know much about this particular algorithm, but I think that this line:
average=m/Alpha;
should be:
average=Alpha/m

Categories