This question already has answers here:
Best way to Format a Double value to 2 Decimal places [duplicate]
(2 answers)
Closed 3 years ago.
I tried doing this
import java.util.Arrays;
public class Array1
{
public static void main (String args [])
{
double [] a1 = {1.3,2.4,5.6,7.8,9.2};
double [] a2 = {1.0,3.4,4.2,5.3,6.7};
double [] a3 = new double[a1.length];
for(int i = 0; i<a3.length;i++)
{
a3[i] = a1[i] - a2[i];
System.out.print("\n"+a3[i]);
}
}
}
However, when it prints, it doesn't print doubles like 1.0. It prints doubles like 0.30000000004.
How may I fix this?
You can do it using String.format("%.1f", a3[i]), here by placing count after . you can decide the how many digits you want to show.
double [] a1 = {1.3,2.4,5.6,7.8,9.2};
double [] a2 = {1.0,3.4,4.2,5.3,6.7};
double [] a3 = new double[a1.length];
for(int i = 0; i<a3.length;i++)
{
a3[i] = a1[i] - a2[i];
String formatted = String.format("%.1f", a3[i]);
System.out.println(formatted);
}
Related
This question already has answers here:
Java: random integer with non-uniform distribution
(10 answers)
Closed 2 years ago.
Can I do the following in java without using external libraries? Maybe with if-else statements?
thanks
import random
print(random.choices(['A', 'B', 'C'], [0.5, 0.3, 0.2]))
Sure. The tools required are:
an instance of java.util.Random
call its nextDouble method.
The algorithm is something like:
First calculate, once-off, the incremental weighting. In your example that would be [0.5, 0.8, 1.0].
Multiply the output of nextDouble with the final weight (here the final weight is 1.0, so not needed. Multiplying by 1.0 doesn't hurt, of course).
loop through the incremental weights and check if the random number you have is less than it. If yes, that's your choice.
Example:
public class WeightedList {
private final char[] choices;
private final double[] weights;
private final Random rnd = new Random();
public WeightedList(char[] choices, double[] weights) {
if (choices.length != weights.length) throw new IllegalArgumentException();
this.choices = Arrays.copyOf(choices);
this.weights = new double[weights.length];
double s = 0.0;
for (int i = 0; i < weights.length; i++) {
this.weights[i] = (s += weights[i]);
}
}
public char get() {
double v = rnd.nextDouble() * weights[weights.length - 1];
for (int i = 0; i < weights.length - 1; i++) {
if (v < weights[i]) return choices[i];
}
return weights[weights.length - 1];
}
}
This question already has an answer here:
What does "possible lossy conversion" mean and how do I fix it?
(1 answer)
Closed 4 years ago.
I'm creating a program that stores doubles in an array and then stores each array in an ArrayList then calculates the average from that ArrayList, but I keep getting a "possible lossy conversion from double to int." in line 5.
I'm new to java so I might be overseeing a simple fix.
public static double calculateAll(List<double[]> allNumbers) {
double average = 0.0;
double total = 0.0;
for(int i = 0; i < allNumbers.size(); i++) {
total += allNumbers.get(i);
}
average = total/allNumbers.size();
return average;
}
I am not sure what you are asking in the question, but I think this is what you are looking for.
public static double calculateAll(List<Double> allNumbers) {
double average;
double total = 0.0;
for (Double allNumber : allNumbers) {
total += allNumber;
}
average = total / allNumbers.size();
return average;
}
You were storing an Array Inside a Collection. So I have changed that to Double note that double is native while Double isn't. You can't have double inside a Collection. and then I have converted the for loop into a foreach loop
Here is how you can call this code.
public static void main(String[] args) {
List<Double> doubles = new ArrayList<>();
doubles.add(0.1);
doubles.add(4.1);
double wat = calculateAll(doubles);
System.out.println(wat);
}
So lets take a note of all the changes we have done.
List<double[]> has been replaced with List<Double>.
List now holds items of instance Double
for(int i = 0; i < allNumbers.size(); i++) was changed to for (Double allNumber : allNumbers) this is just a basic for-each loop.
Honestly I would just use java 8 for this, We can do this in 1 line!
public static double calculateAll(List<Double> allNumbers) {
return allNumbers.stream().mapToDouble(e -> e / allNumbers.size()).sum();
}
This question already has answers here:
Float and double datatype in Java
(9 answers)
Closed 6 years ago.
Can someone show me an example of example how I could use Double in the following code?
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
int myFirstNumber = (5+10) + (6*8);//Declaring an integer myFirstNumber
int mySecondNumber = 10;
int myThirdNumber = 3;
int myTotal = myFirstNumber + mySecondNumber + myThirdNumber;
System.out.println(myFirstNumber);//prints variable myFirstNumber
System.out.println("myFirstNumber ");//
System.out.println(myTotal);
}
}
Use either float or double (or their boxed counterparts, Float and Double) when you need to deal with non-integer values. The code you posted has no apparent need for that, so it's hard to answer your question. But one possibility would be if you wanted to compute, say, the average of the three numbers:
public class HelloWorld { public static void main(String[] args) {
System.out.println("Hello, World!");
int myFirstNumber = (5+10) + (6*8);//Declaring an integer myFirstNumber
int mySecondNumber = 10;
int myThirdNumber = 3;
int myTotal = myFirstNumber + mySecondNumber + myThirdNumber;
float average = myTotal / 3.0f;
System.out.println(myFirstNumber);//prints variable myFirstNumber
System.out.println("myFirstNumber ");//
System.out.println(myTotal);
System.out.println(average);
}
As to when to use float vs. double (the title of your question), use double when you can tolerate less rounding error than you get with float.
I passed the var array as an argument to the quadraticalc method and used it to perform operations but i want to return two values..but giving me errors
package testingequality;
import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
//comparison ();
double [] var = new double [3];
int counter;
Scanner input = new Scanner (System.in);
for (counter = 0; counter< var.length; counter++)
{
System.out.println ("Input value for a,b,c");
var [counter] = input.nextDouble();
}
double [] sum = quadraticalc (var);
for (int i = 0; i < sum.length; i++)
{
System.out.println (sum [i]);
}
}
public static double [] quadraticalc (double [] var)
{
double a,b,c,d,e;
double [] x = new double [2];
a = var [0];
b = var [1];
c = var [2] ;
d = (b*b)-(4*a*c);
e = Math.sqrt(d);
double x1 = (-b + e)/ (2 * a);
double x2 = (-b - e)/ (2 * a);
x [0] = x1;
x [1] = x2;
return x;
}
}
I made a little change to the code and i was able to get the right answer now.. thanks to all that contributed
Instead of printing the array reference, you should print the values inside the array.
Change:
System.out.println (sum);
to:
System.out.println (sum[0]);
System.out.println (sum[1]);
Going out on a limb here ...
You need to pretty print the contents of the array. Try
Arrays.toString(sum)
But, of course, you could have other issues ...
So I ran your code. There are no errors, but I think you're getting something printed like [D#330bedb4 and you believe it is an error. Rather this is perfectly acceptable behavior. At
System.out.println (sum);
I think that you expect the numbers to be printed. In reality though, Java prints the array object, which doesn't have a pretty string representation. So instead, you want to print the doubles that are found within the array. Something like this will do
for (int i=0; i < sum.length; i++) {
System.out.println(sum[i]);
}
I got NaN when I did this, so there must be something wrong with quadraticalc and how you are calculating values.
EDIT: This is because if d is negative, e (the sqrt of d) will not be a real number. If you are calculating the quadratic, you maybe want a check for that.
I changed your quadratic function for easier readability to
public static double [] quadraticalc (double [] var)
{
double a = var [0];
double b = var [1];
double c = var [2];
System.out.println("a = " + a + ", b = " + b + ", c = " + c);
double root1 = (-b + Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a);
double root2 = (-b - Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a);
return new double[] { root1, root2 };
}
Example run (I printed the a, b, c, d, and e values for visibility)
Input value for a,b,c
10 100 10
Input value for a,b,c
Input value for a,b,c
a = 10.0, b = 100.0, c = 10.0, d = 9600.0, e = 97.97958971132712
-0.10102051443364388
-9.898979485566356
These answers are correct and can be verified # http://www.math.com/students/calculators/source/quadratic.htm
This question already has answers here:
Java exponent error at 2^31 power [duplicate]
(2 answers)
Closed 8 years ago.
So, I have this code, which works fine for the first 4 numbers, but then it gives a wrong number, What's the problem? (I know I can also use Math.pow, but I wanted to try doing it myself first)
public static void main(String [] args){
int number = 98;
int result = number;
int exponentt = 5;
int exponent = exponentt--;
System.out.println(Math.pow(number, exponent));
for (int i = 0; i < exponentt ;i++) {
result = result * number;
System.out.println(result );
}
}
Console:
9604
92236816
449273376
Switch your int number to a long and you will get the right result.
public static void main(String [] args){
**long** number = 98;
**long** result = number;
int exponentt = 5;
int exponent = exponentt--;
System.out.println(Math.pow(number, exponent));
for (int i = 0; i < exponentt ;i++) {
result = result * number;
System.out.println(result );
}
}
It's going outside of the range for the int and giving you weird results. int can only store up to 2,147,483,647 -- 98^4 is well over that (9,039,207,968)