Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- /**
- *
- * @author JakeFromStateCS
- */
- public class DoubleDifference {
- public static void main(String[] args) {
- double testArray1[] = new double[10];
- for( int i = 0; i < 10; i++ ) {
- testArray1[i] = getRandomDouble( -10.0, 10.0 );
- }
- double difference = getDifference( testArray1 );
- System.out.println( "The difference is: " + difference );
- }
- /*
- getRandomDouble:
- Input:
- lowerBound: The lowest possible number
- upperBound: The highest possible number
- Purpose:
- Generates a random double between the lower and upper bounds
- Returns:
- double result: The result of the random generation
- */
- public static double getRandomDouble( double lowerBound, double upperBound ) {
- //Returns a random double between 0 and 1
- double randomDouble = new Random().nextDouble();
- //If lowerBound is 2, upperBound is 10 and randomDouble is 0.3
- // 2 + ( 0.3 * ( 10 - 2 ) )
- // 2 + ( 0.3 * 8 )
- // This shifts the number scale to the right
- double result = lowerBound + ( randomDouble * ( upperBound - lowerBound ) );
- return result;
- }
- /*
- getDifference:
- Input:
- input: An array of doubles
- Purpose:
- Return the difference between the highest and lowest value in an array of doubles
- Returns:
- double: The difference between the largest and smallest value in an array of doubles
- */
- public static double getDifference( double input[] ) {
- //We want to set the smallest value to the largest value possible
- //This way, every value will be lower than or equal to this one
- double smallestValue = Double.MAX_VALUE;
- //We want to set the largest value to negative Double.MAX_VALUE
- //This will ensure that it is not possible for there to be a smaller value
- double largestValue = -Double.MAX_VALUE ;
- //Loop through each element of the array
- for( int key = 0; key < input.length; key ++ ) {
- double value = input[key];
- if( value > largestValue ) {
- largestValue = value;
- }
- if( value < smallestValue ) {
- smallestValue = value;
- }
- System.out.println( "input[" + key + "] = " + value] );
- }
- System.out.println( "Largest: " + largestValue );
- System.out.println( "Smallest: " + smallestValue );
- return largestValue - smallestValue;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement