Why doesn't the average come out a double? [duplicate] - java

This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 7 years ago.
/**
* Write a description of class GUI here.
*
* #author (your name)
* #version (a version number or a date)
*/
import java.util.*;
public class GUI
{
// instance variables - replace the example below with your own
public static void main(String [] args){
Scanner r = new Scanner(System.in);
int x;
int y;
int z;
System.out.println("x");
x = r.nextInt();
System.out.println("y");
y = r.nextInt();
System.out.println("z");
z = r.nextInt();
double t = (x+y+z)/3;
System.out.println("result " + t);
}
}
Hello, above is my code.
I purposely made it int x,y,z to test the program.
When I input for example (when running the program) :$x = 1, 1, 3$ it rounds the answer always! Why is this?

This is an example of Java's integer division, which must always return another integer. It truncates any decimal result. This occurs even though the result is assigned to a double.
Use a double literal when dividing to force floating-point division.
double t = (x+y+z)/3.0;

Related

Why does division in Java displayonly 0? [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 2 years ago.
I have the following method in a Java program:
public void Div(int a, int b){
//exception in order to check if the second argument is 0
try{
int div1 = (a / b);
double div = div1;
System.out.println("The division of the two numbers is: " + div);
}
catch(ArithmeticException e){
System.out.println("You can't divide a number by 0");
}
This only works if numerator is larger than the denominator ( e.g 8/2). If the numerator is smaller than the denominator I get a result of 0.0 (e.g. 2/8).
What can I do to make it work?
It's happening because of integer division. You can cast one of the arguments to double and store the result to a double variable to fix the issue.
public class Main {
public static void main(String[] args) {
div(5, 10);
}
public static void div(int a, int b) {
try {
double div = (double) a / b;
System.out.println("The division of the two numbers is: " + div);
} catch (ArithmeticException e) {
System.out.println("You can't divide a number by 0");
}
}
}
Output:
The division of the two numbers is: 0.5
On a side note, you should follow Java naming conventions e.g. the method name, Div should be div as per the Java naming conventions.
(a/b) You're doing integer division. You need to typecast to other data types that can store decimal like double.
double div = (double) a / b;

Java pow without rounding up the final value [duplicate]

This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 3 years ago.
I am trying to write a formula for one of my functions where I need to raise my X to power of Y. The values I am working with are really small and will get rounded up as soon as I use pow function of Math, BigInteger and BigDecimal.
For example if I use the following values it will return 1000 whereas it should return 1006.931669!
T0 = 1000, TN = 1, k = 1, N = 1000
double X = (finalTemp/initialTemp);
double A = Math.pow(X, (k/n));
double tk = initialTemp * A;
They are being divided in integer arithmetics. So dividing integer a by integer b you get how many times b fits into a, If the types of the operands are double, then "real" division is performed.
double X = (finalTemp/(double)initialTemp);
double A = Math.pow(X, (k/(double)n));
double tk = initialTemp * A;
the output is correct according to calculator
public class Main
{
public static void main(String[] args) {
double finalTemp = 1.0;
double initialTemp = 1000.0;
double k = 1.0;
double n = 1000.0;
double X = (finalTemp/initialTemp);
double A = Math.pow(X, (k/n));
double tk = initialTemp * A;
System.out.println(tk);
}
}
output is 993.1160484209338

How do I square Sin and Cos in Java? [duplicate]

This question already has answers here:
Quickly square a double
(3 answers)
Closed 6 years ago.
I need help with this java exercise. The instructions are
Write a program that uses Math.sin() and Math.cos() to check that the
value of sin2θ + cos2θ is approximately 1 for any θ entered as a
command-line argument. Just print the value. Why are the values not
always exactly 1?
My code so far (It is my first code so please no harsh judgement).
public class math {
public static void main(String[] args) {
//Changes the data types from string to double
double a = Double.parseDouble(args[0]);
double b = Double.parseDouble(args[1]);
//Does the calculation math functions
double s = 2*Math.sin(a);
double c = 2*Math.cos(b);
double target = .9998; // var for comparing if less than 1
double answer = s + c;
// Prints the answer and checks whether its less than 1
System.out.println(answer < target);
System.out.println(answer);
}
}
I guessed on squaring the sin and cos. If anyone has quick suggestion on how to square sin and cos and if there is an error in my little program I will appreciate your help.
I think what you are going to do is this. You got this wrong meaning of "sin^2θ". It's actual meaning is sin2θ. And same for cos. This is the code you are looking for.
double a = Double.parseDouble(args[0]);
//Does the calculation math functions
double s = Math.pow(Math.sin(a),2);
double c = Math.pow(Math.cos(b),2);
double target = .9998; // var for comparing if less than 1
double answer = s + c;
// Prints the answer and checks whether its less than 1
System.out.println(answer < target);
System.out.println(answer);
you have one theta so: you need just args[0] and not args[1].
so a=b in your sample code.
squaring the sin and cos and adding:
Option 1:
double stheta = Math.sin(theta);
double ctheta = Math.cos(theta);
double answer = stheta*stheta + ctheta*ctheta;
Option 2:
double s2 = Math.pow(Math.sin(theta),2);
double c2 = Math.pow(Math.cos(theta),2);
double answer = s2 + c2;
working sample code:
package javaapplication1;
public class JavaApplication1 {
public static void main(String[] args) {
double theta = Double.parseDouble(args[0]);
double stheta = Math.sin(theta);
double ctheta = Math.cos(theta);
double answer = stheta*stheta + ctheta*ctheta;
System.out.println(answer);
}
}
and see:
Java - does double and float percision depend on the machine?
Test Number For Maximum Precision In Java
Floating point numbers are not exact representations. Double precision 64 bit IEEE floating point representation only gives 17-18 digits, so you always compare differences to a tolerance.
I would recommend multiplying a number by itself for squaring over using Math.pow().
Here's a JUnit test that shows how I'd do it:
package math;
import org.junit.Test;
import org.junit.Assert;
/**
* Created by Michael
* Creation date 6/25/2016.
* #link https://stackoverflow.com/questions/38024899/how-do-i-square-sin-and-cos-in-java
*/
public class MathTest {
public static final double TOLERANCE = 1.0e-8;
#Test
public void testUnitCircleIdentity() {
int n = 10;
double t = 0.0;
for (int i = 0; i < n; ++i) {
double s = Math.sin(t);
double c = Math.cos(t);
double actual = s*s + c*c;
Assert.assertEquals(1.0, actual, TOLERANCE);
t += Math.PI/n;
}
}
}

Division of two static integers always returning 0% ratio [duplicate]

This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 9 years ago.
My code:
public class Test {
public static int l = 29;
public static int w = 16;
public static int total = w + l;
public static int result = w / total;
public static int Result = total * 100;
public static void main(String[] args) {
System.out.println("You're W/L ratio is: " + (Result) + "%"); // Display the string.
}
}
Response in console: You're W/L ratio is: 0%
You're doing int division which always returns an int and so w / total will always be 0 since total is always greater than w. Do the multiplication by 100 first.
int result = (w * 100) / total;
Also you will want to learn and use java naming rules. Variable names should begin with a lower case letter.
Do the calculation by casting w and total to double, or just make them double to begin with. For the first option:
public static double result = (double)w / (double)total;
whenever you do division when both numbers are integers, in result you will get integer in return.
which actually means you will get floor value of (a/b); ie:
1/2=0 as 1/2=> 0.5> floor of 0.5= 0;
3/4=0 as 3/4=> 0.75> floor of 0.75= 0;
etc

For loop, dividing one [duplicate]

This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 7 years ago.
I have tried this in Javascript and have gotten my answers, but the answer I need must be more exact. I am trying to divide 1 by every number between 2 and 1000, and simply print them.
public static void main(String [] args) {
for (int i=2;i<=1000;i++){
double g = (1/i);
System.out.println(g); // print "1/1,2,3,4.....1000"
}
}
I haven't done Java in a while, so I forget my correct variable names.
Since both 1 and i are integers, integer division is being used. Either 1 or i need to be double in the 1/i section of your code so that integer division is not used. You can do something like 1.0/i or 1/((double) i) to ensure that float division is used instead.
replace 1 by 1.0D that will result into double
try this
public static void main ( String args[] ) {
for (int i=2;i<=1000;i++){
double g = (1.0/i);
System.out.println("1/"+ig);
}
output:
0.5
0.3333333333333333
0.25
0.2
0.16666666666666666
0.14285714285714285
0.125
.
.
.
.
I would do something like this (note you can have as many digits of precision as you like) utilizing BigDecimal.
public static void main(String[] args) {
java.math.BigDecimal ONE = java.math.BigDecimal.ONE;
// 50 digits of precision.
java.math.MathContext mc = new java.math.MathContext(50);
for (int i = 2; i <= 1000; i++) {
java.math.BigDecimal divisor = new java.math.BigDecimal(i);
java.math.BigDecimal result = ONE.divide(divisor, mc);
result.round(mc);
System.out.printf("%d/%d = %s\n", 1, i,
result.toString());
}
}

Categories