So I need to use the class org.apache.commons.math3.stat.StatUtils to compute the mean of an array of float, but the input array should be an array of double.
How can I convert float[] into a double[]?
You can solve your problem by defining logical steps that all together achieve the goal:
Create a double[] of same length as the float[]
Iterate over the float[] and save the values one by one in the corresponding index in the double[]
Traditionally or pre Java 8 one would go this way:
final double[] doubleArray = new double[floatArray.length];
for (int i = 0; i < floatArray.length; i++) {
doubleArray[i] = floatArray[i]; // no casting needed
}
When using Java 8 you can use the Stream API for this to get a neater solution:
IntStream.range(0, floatArray.length).forEach(index -> doubleArray[index] = floatArray[index]);
Possible use as function:
public static double[] convertToDouble(final float[] values) {
final double[] result = new double[values.length];
IntStream.range(0, values.length).forEach(index -> result[index] = values[index]);
return result;
}
Convert each value in array to double.
Float is shorter than double, so You don't have to worry about losing precision.
Create array of doubles of the same length as float array.
Then, You can implict convert array of float to array of double.
public double[] answer(float[] array){
double[] newArray = new double[array.length];
for ( int i = 0 ; i < array.length ; i++ )
newArray[i] = (double) array[i];
return newArray;
}
Related
I have to get an float[] array from an TockaXY[] array.
Example of TockaXY[] with 4 elements:
[60.039005,86.44917][96.53153,41.086178][19.988914,31.67395][96.84925,41.90731]
but I need an float[]. Tried:
for (int i = 0; i < objectArray.length; i++)
floatArray[i] = (Float)objectArray[i];
But I get error cannot Cast.
Any Ideas?
If i understood it right, you have an array within an array.
if you want to keep it this way than you have to create another array within an array
so;
float floatArray[][]; //declare a 2D array
floatArray = new float[4][2]; //make it's length same as yours
for (int i = 0; i < objectArray.length; i++){
for(int j =0; j<objectArray[i].length; j++){
//parse each value as float, and assign it to your new array
floatArray[i][j] = Float.parseFloat(objectArray[i][j]);
}
}
First of all your given element is not array, its array of array.
You can try this to convert Object[][] to Float[][].
Object[][] objectArray = { { 60.039005, 86.44917 }, { 96.53153, 41.086178 }, { 19.988914, 31.67 },
{ 96.84925, 41.90731 } };
Float[][] floatArray = new Float[objectArray.length][2];
for (int i = 0; i < objectArray.length; i++) {
floatArray[i][0] = ((Double) objectArray[i][0]).floatValue();
floatArray[i][1] = ((Double) objectArray[i][0]).floatValue();
}
System.out.println(floatArray);
Assuming TockaXY is something like
public sclass TockaXY {
private float x;
private float y;
//Constructors, getters, setters etc.
#Override
public String toString() {
return "["+ x + ", " + y + "]";
}
}
and you want a float[] containing the values of x and y from each element of a TockaXY[], the size of the float[] must be 2 * size of TockaXY[].
float [] floatArray = new float[objectArray.length * 2];
for (int i = 0, j=0; i < objectArray.length; i++) {
floatArray[j++] = objectArray[i].getX();
floatArray[j++] = objectArray[i].getY();
}
This: (SomeType) someExpr; is called a cast operation. Unfortunately, there are 3 completely different things that java can do, that all look exactly like this. A real guns and grandmas situation!
Casts can convert things, or can assert generics in types, or can coerce types itself. The latter two, at runtime, do nothing (maybe throw ClassCastException), it's just ways to tell the compiler you know what you are doing; to treat things as different types.
The ONLY one that converts anything is the 'type conversion' mode, and that one only kicks in if both the type in the parentheses and the expression you're applying it on are primitive (auto-unboxing may kick in, but it ends there).
Float is not primitive (float is primitive), so you're not doing a type conversion here, but your question makes it sound like you think you are.
Okay, and.. how do I fix my code?
It looks like TockaXY is a class that looks something like:
class TockaXY {
public float x, y;
}
From your question it is unclear what you want here. Do you want all 8 floats in an 8-sized float array? Do you only want the 'x' elements? Only the 'y' elements?
A TockaXY is not a float (it's a coordinate), so this is not easy, you'd have to program that. For example:
TockaXY[] in = ...;
float[] fs = new float[in * 2];
for (int i = 0; i < in.length; i++) {
fs[i * 2] = in[i].x;
fs[(i * 2) + 1] = in[i].y;
}
I have a function that generates random arrays:
private static List<Integer> randomIntegerArray(int n) {
int[] array = new int[n];
for(int i = 0; i < array.length; i++) {
array[i] = (int)Math.random();
}
return array;
}
I'm getting the following error:
incompatible types: int[] cannot be converted to java.util.List
I'm not sure what the issue is here. This is an incredibly simple bit of code that I can't seem to get to work.
You're returning List<Integer>, but you're creating an int[]. They're completely different things! try this instead:
private static List<Integer> randomIntegerArray(int n) {
List<Integer> list = new ArrayList<>();
for(int i = 0; i < n; i++) {
list.add((int) Math.random()); // always returns 0
}
return list;
}
Or if you definitely want to use an array, change the method's declaration:
private static int[] randomIntegerArray(int n)
And be aware that Math.random() returns a value between 0 and 1, if you convert it to an int it'll always be 0.
You can have simpler code that actually produces random integers instead of zeros by directly using the Random class:
private static List<Integer> randomIntegerArray(int n) {
return ThreadLocalRandom.current().ints(n).boxed().collect(Collectors.toList());
}
This may return any Integer value; you can specify a range with additional arguments to the ints() method.
An alternative to Oscar's answer would be:
private static int[] randomIntegerArray(int n) {
int[] array = new int[n];
for(int i = 0; i < array.length; i++) {
array[i] = (int)Math.random();
}
return array;
}
As others have said, a List of type Integer is not the same thing as an array of type int.
Probably this wouldn't be the best choice but also works, altough you'll get always a zero list of integers as Peter Lawrey says:
private static List<Integer> randomIntegerArray(int n) {
Integer[] array = new Integer[n];
for(int i = 0; i < array.length; i++) {
array[i] = Double.valueOf(Math.random()).intValue();
}
return Arrays.asList(array);
}
Your error tells you that arrays and list are not compatible, a quick search would have shown you ways to convert one to the other like Arrays.asList ().
Secondly Math.random returns a random number between 0.0 and 0.9 so you need to multiply by the number you want.
You may need to go through a quick tutorial on Java first.
All the best.
I'm trying to covert an array of strings into an array of doubles.
I'm fairly familiar with ArrayList<>() , but i see there is in an example code give, double[].
example: list = ["1" , "2" , "3"]
desired return: number = [1 , 2 , 3]
public double[] ConversionNumber
{
double[] sequence = new double[list.size()];
for(String element:list){
double val = Double.parseDouble(element);
sequence.add(val)}
return sequence;
when i do this, i get an error in Bluej compiler: "cannot find symbol- method add(double).
What is a good way to solve this (i'm a beginner at Java).
thanks!
If list is an array, then list.size() would fail. I think we can assume it should be a List<String>. And you access an array by index. Also, I assume it should be an argument to your method. Next, Java convention for methods names is camelCase.
public double[] conversionNumber(List<String> list) {
double[] sequence = new double[list.size()];
int pos = 0;
for (String element : list) {
double val = Double.parseDouble(element);
sequence[pos++] = val; // <-- post-increment
}
return sequence;
}
Generally, if you're working with Collections, you work with collections the whole way. It's bad form to use Lists for one thing, but arrays for another. So it's advisable to do this with a List<Double> instead of a double[]
public List<Double> parseDoubles(List<String> strings) {
List<Double> doubles = new ArrayList<>(strings.size());
for(String string : strings) {
doubles.add(new Double(string));
}
return doubles;
}
Below code will work for your case:
java.util.List<String> list = java.util.Arrays.asList("1", "2", "3");
public double[] ConversionNumber() {
double[] sequence = new double[list.size()];
int i = 0;
for(String element:list){
double val = Double.parseDouble(element);
sequence[++i] = val;
}
return sequence;
}
The error happens because arrays dont have an 'add' method. You will want to do something like:
double[] sequence = new double[list.length];
for(int i = 0; i < list.length; i++){
sequence[i] = Double.parseDouble(list[i]);
}
If list is an actual List not a String[] as I assumed, you would do:
double[] sequence = new double[list.size()];
for(int i = 0; i < list.size(); i++){
sequence[i] = Double.parseDouble(list.get(i));
}
Change your code here
for(String element:list){
double val = Double.parseDouble(element);
sequence.add(val)
}
to this if your list is a List:
for(int i=0;i<list.size();i++){
double val = Double.parseDouble(list.get(i));
sequence[i]=val;
}
if your list is an Array, then change to this:
for(int i=0;i<list.length;i++){
double val = Double.parseDouble(list[i]);
sequence[i]=val;
}
I get the five double data type values from five different function.Without adding those value into array is there any efficient java code for get the maximum value from that five value set.
double d1=r1.function1();
double d2=r1.function2();
double d3=r1.function3();
double d4=r1.function4();
double d5=r1.function5();
double[] d=new double[5];
for(int i=0:i<5;i++){
d[i]="d"+i;
}
double x=max(d);
public static double max(double[] t) {
double maximum = t[0]; // start with the first value
for (int i=1; i<t.length; i++) {
if (t[i] > maximum) {
maximum = t[i]; // new maximum
}
}
return maximum;
}
Without going this much effort is there any efficient way to get the maximum value from above double type data set? And also when adding value to the loop there also some error represent in d[i]="d"+i; part. Please provide me better solution.
You can use ArrayList<Double> and than
ArrayList<Double> alist=new ArrayList<Double>();
//Add double values to this list
You can use Collections.max(alist) to get maximum value and Collections.min(alist) to get minimun value.
Collections.max(Arrays.asList(d));
if would be more efficient if instead of having d as an array. have it as list to begin with.
You could use varargs instead of an array.
public double max(double... values) {
int max = -Double.MAX_VALUE;
for(double value : values) {
if(value > max) {
max = value;
}
}
return max;
}
Then you call your method like double max = max(d1, d2, d3, d4, d5);
EDIT :
Your lines
for(int i=0:i<5;i++){
d[i]="d"+i;
}
don't work, because "d"+i will create a String due to string concatentation and will not be the double variable with that name.
You cannot fill your array like this.
You will have to do:
d[0] = d1;
d[1] = d2;
d[2] = d3;
d[3] = d4;
d[4] = d5;
In Java 8:
Arrays.stream(darray).max().getAsDouble()
Full method (in our case, return zero if the array is empty; change your default as desired).
public static double max(final #Nullable double... values)
{
return ((values != null) && (values.length > 0)) ? Arrays.stream(values).max().getAsDouble() : 0;
}
This method can be called with either an array or varargs parameter:
double[] darray = new double[]{43.7, 65.2, 99.1, 87.6};
double max1 = max(darray);
double max2 = max(1.2, 3.4, 5.6);
You dont have to put them in array yourself, let Java do that part of work using varargs:
public static double max(Double... numbers){
double max = numbers[0];
for(int i = 0; i < numbers.length; i++){
if(numbers[i] > max){
max = numbers[i];
}
}
return max;
}
You can add d1,d2,d3,d4,d5 to TreeSet
Set<Double> set=new TreeSet<>(); // while you adding set will be sorted
// add values to set
List<Double> setAsList=new ArrayList(set); // convert set to list
System.out.println(setAsList.get(setAsList.size()-1)); // last value is the max
List <Double> d = new ArrayList<>();
d. add (d1);
d. add (d2);
d. add (d3);
d. add (d4);
d. add (d5);
Double max=Collections. max (d);
In Java 8,
java.util.Arrays.parallelSort(d).get(d.size-1)
to get max value in (merge sorted) array.
Got this code (not working):
for (int i = 0; i < splitSource.length; i++) {
float[] nr = Float.parseFloat(splitSource[i]);
}
I have an collection of strings...
List<String> stringCollection = new ArrayList<>();
Previously, every string from the list is treated separately extracting from it the necessary and unnecessary characters and the final result is a string of pure numbers.
Now, I need to convert those numbers from String into Float, but i get the error of "float cannot be converted to float[]"...
float[] nr= new float[splitSource.length];
for (int i = 0; i < splitSource.length; i++) {
nr[i] = Float.parseFloat(splitSource[i]);
}
Float.parseFloat returns single float number, not array. Also, declaring float[] nr inside for cycle makes no sense. Result will be lost when cycle ends.
The method Float.parseFloat(String) delivers a float. Not an array of float. So just write
float[] nr = new float[splitSource.length];
for(...) {
nr[i] = Float.parseFloat(splitSource[i]);
}