i’m trying to build an data structures and algorithms program using java. and i wanna ask if anyone know How do i calculate the percentage increase or decrease in a array. i try this code–but apparently its not the correct way
JavaScript
x
public class test{
static float checkMov(int arr[], int n) {
float var1, var2, result = 0;
var1 = arr[0];
var2 = arr[1];
// Calculate successive change of 1st 2 change
result = var1 + var2 + ((var1 * var2) / 100);
// Calculate successive change
// for rest of the value
for (int i = 2; i < n; i++) {
result = result + arr[i] + ((result * arr[i]) / 100);
}
return result;
}
}
JavaScript
import static test.testt.checkMov;
public class tester {
public static void main(String[] args)
int[] arr = {1931534,1933628,1935714,1925709,1923754,1923578,1923049,1928556,1928289,1924857};
int N = arr.length;
// Calling function
float result = checkMov(arr, N);
System.out.println("Percentage change is = " + result + " %");
}
}
Run-> Percentage change is = Infinity %
Advertisement
Answer
Here you’re dealing with the numbers, which could go in the larger values. Datatype float
has limited range to handle the numbers between 3.40282347 x 10e38 and 1.40239846 x 10e-45
. So change the method return type of checkMov
to double. Also handle the values in double
, which ranges between 1.7976931348623157 x 10e308 and 4.9406564584124654 x 10e-324
.
JavaScript
static double checkMov(int arr[], int n) {
double var1, var2, result = 0;
var1 = arr[0];
var2 = arr[1];
// Calculate successive change of 1st 2 change
result = var1 + var2 + ((var1 * var2) / 100);
// Calculate successive change
// for rest of the value
for (int i = 2; i < n; i++) {
result = result + arr[i] + ((result * arr[i]) / 100);
}
return result; // This returns 7.0955315970304415E44
}