GUI 6.2.10

6.5. User Functions

User Functions are an extensibility feature of newFASANT that allows the user to write general purpose numerical functions using the Java programming language. Those functions can then be used in several other features of newFASANT as a way for making easier and faster to work with numerical data or other kind of data, such as definining curves or surfaces based on functions or during the post-process.

6.5.1. User Functions editor

The user functions editor is an integrated environment where you can create, edit or delete user functions that can later be used in newFASANT. Open Tools | User Functions, to start the User Functions editor.

The User Functions menu item.

Figure: the User Functions menu item.

This is the User Functions Editor. On your left, there is a sidebar with the different Java files currently registered in newFASANT. There is a main container where the editor will appear once a file is opened. At the top, a toolbar lets you perform several actions on the files or on the opened user functions.

The User Functions tab panel.

Figure: The User Functions tab panel.

The following buttons are available on the toolbar for working with user function files.

User Functions toolbar (left button group).

Figure: User Functions toolbar (left button group).

  • New user function: creates an empty and unsaved user function.
  • Open function: once a function is selected in the sidebar, it will open the selected function in the editor.
  • Import user function: if you have a .java file on your file system that you want to quickly import into newFASANT for later usage, such as a user function downloaded from our Scripts Center, you can use this button to copy a Java file into your user functions directory, instead of manually copying and pasting the contents.
  • Open user functions directory: this will open your file explorer at the folder where all the Java user functions files are actually stored at the newFASANT installation directory.

When a user function is opened, the following buttons are also available.

User Functions toolbar (right button group).

Figure: User Functions toolbar (right button group).

  • Save user function: saves the contents of the user function editor to disk.
  • Rename user function: it will ask the user for a new name for this user function file. Note that the names given to the user function files are only relevant to the user as a way for managing the content of the different user function files added to newFASANT. There is no real difference on how the user interface will later execute these functions depending on the name.
  • Delete user function: it will ask the user for confirmation, before deleting the selected user function file from the hard disk. This operation cannot be undone. Keep in mind that once an user function is deleted, projects that depend on that user function may behave unexpectedly unless it is created again. User functions are not saved in project files.
  • Undo: undo the latest modification made to the editor.
  • Redo: redo the latest modification undone.

To open a user function, double click it from the sidebar, or click it on the sidebar and then press the Open User Function button in the toolbar. This will display the file in the editor. The editor can keep multiple files opened at the same time.

The User Functions editor with a few files opened.

Figure: The User Functions editor with a few files opened.

You can close a user function by clicking at the Close (X) button on the tab for the user function you want to close. Additionally, you can close the User Functions editor in order to close all the user functions at once and remove the editor from your desktop interface. Note that if you have unsaved changes it will ask for confirmation.

Asking for confirmation before closing the User Functions editor because there are unsaved changes.

Figure: Asking for confirmation before closing the User Functions editor because there are unsaved changes.

6.5.2. Example Functions

The general syntax for any Java function can be summarized as:

  <output> <functionName> ( <inputs> ) {
    // Comment: Add your Java code here
  }

The next elements are identified:

  • Output: It specifies the type of data that the function will return. The most common type will be double or double [], that is, real numbers or arrays of real numbers.
  • functionName: Name that defines the function. This name is used to invoke the function.
  • inputs: Arguments required for invocating the function. Any type of argument is allowed, for example: "()" for empty arguments; "(int n)" for an integer argument; or "(double start, double end, int samples)" for a real range defined by its boundary values and the number of samples."

Multiple functions are included in the following:

Function examples:

  // Calculate the square of 'a'
  double square(double a){
    return a*a;
  }
  // Calculate the modulus of vector (x,y,z)
  double modulusVector(double x, double y, double z){
    return Math.sqrt(x*x + y*y + z*z);
  }
  // Calculate if 'a' is prime
  int prime(int a){
    // returns 1 if 'a' is prime, else return 0
    for(int i=2 ; i<=(a/2) ; i++) {
      if(a % i == 0) {
        return 1;
      }
    }
    return 0;
  }
  // Calculate the a-th number of the Fibonacci sequence
  int fibonacci(int a){
    int fib_n = 1;   // fibonacci(0)
    int fib_m = 1;   // fibonacci(1)
    int fib_i;	

    if (a < 0) {
      return 0;
    }
    if (a < 2) {
      return 1;
    }
    for(int i=2 ; i<=a ; i++) {
      // calculate fibonacci(i)
      fib_i = fib_n + fib_m ;
      fib_n = fib_m;
      fib_m = fib_i;
    }
    return fib_i;
  }
  // Calculate the 'a' factorial (a!)
  double factorial(int a){
    double acc = 1;
    for(int i=1 ; i<=a ; i++) {
      acc = acc * i;
    }
    return acc;
  }
  // Calculate the binomial coefficients function
  double binomial(int m, int n){
    return (factorial(m)) / (factorial(n) * factorial(m-n));
  }

6.5.3. Applications

In this section, the main applications of the User Functions are summarized.

  • Calculator
  • Plot Viewer
  • Geometry Parameters
  • Geometry Creation
  • FMCW
  • Reflectarray Layout

Take the following user functions file that will be used in the following sections. You can copy and paste it into a new user function on your editor if you want to try these by youself. Press New user function to create a blank file, then write the contents of the user function file, and then press Save to save the file. It will ask you for the name to give to the user function.

Figure: File name to use for this user function.

//Returns a random value between 0 and 1
double randomValue() {
    return Math.random();
}

//Returns a random value between 'min' and 'max'
double randomValue(double min, double max) {
    double size = max - min;
    return min + size*Math.random();
}

//Returns an array of random values between 0 and 1
double[] randomArray(int size) {
    double [] array = new double[size];
    for (int i = 0; i < size; i++){
        array[i] = randomValue();
    }
    return array;
}

//Returns an array of random values between 'min' and 'max'
double[] randomArray(double min, double max, int size) {
    double [] array = new double[size];
    for (int i = 0; i < size; i++){
        array[i] = randomValue(min, max);
    }
    return array;
}

//Generate linearly spaced vector
double[] linspace(double min, double max, int samples) {
    double step = (max-min)/(samples-1);
    double[] range = new double[samples];
    for(int i=0; i<samples; i++) {
        range[i] = min + (step*i); 
    }
    return range;
}

//Return an array with the values of applying the 'sin' operation 
//to the input arguments
double[] sinValues(double[] x) {
    double[] y = new double[x.length];
    for(int i=0; i<y.length; i++) {
        y[i] = Math.sin(x[i]); 
    }
    return y;
}

User function example file.

6.5.3.1. Calculator

Mathematical operations that use any defined user function can be used within the Calculator tool.

Click on Tools - Calculator menu. Invoke any user function, as shown in the below figure. Remember that an user function file with the considered functions is required for this example, as mentioned in the introduction section.

Using user functions in the Calculator

6.5.3.2. Plot Viewer

Values returned by user functions can also be plotted. To do that, the values must be previously computed in the Calculator tool.

Click on Tools - Calculator menu. Invoke any user function that return an array of values, and the use the plot sentence to visualize the values in the Plot Viewer, as shown in next figure. Remember that an user function file with the considered functions is required for this example, as mentioned in the introduction section.

Using user functions in calculator to invoke the Plot Viewer

The plot sentence open the Plot Viewer with the selected data in a plotted serie (named plot1). Mathematical operations can be applied to the serie to obtain new plots, as shown in the below figure.

Using user functions in the Plot Viewer

6.5.3.3. Geometry Parameters

User functions that return a double value can be used in the definition of geometrical parameters.

Click on Geometry - Parameters - Define Parameters menu. Remember that an user function file with the considered functions is required for this example, as mentioned in the introduction section.

Create the three parameters that are shown in next figure. Note that it is only an trainning example without further purposes, as the random (and then the y) parameters depend on the randomValue(), so its values will be different whenever the simulation step changes.

Using user functions in the Define Parameters panel

Then, the defined parameters may be used for any geometrical operation. In the below figure, a line with variable end-point has been created.

Line with random end point

6.5.3.4. Geometry Creation

User functions that return a double value can be used in most of geometrical operations. Remember that an user function file with the considered functions is required for this example, as mentioned in the introduction section.

Most of commands may work with user functions. This section show some examples with the commands where the user functions are especially useful.

    • curveFunction: The randomValue(min, max) has been used to create a sinusoid (with random noise) curve.

Using user functions in the curveFunction command

    • surfaceFunction: The randomValue() has been used to create a sinusoid (with random noise) surface.

Using user functions in the surfaceFunction command

6.5.3.5. FMCW

FMCW (Frequency-Modulated Continuous-Wave) is a postprocessing of the GTD-PO Module. Any project with Doppler effect enabled can perform this postprocess. A user function is required to introduce the signal frequency in the time domain.

Go to GTD-PO Module FMCW

6.5.3.6. Reflectarray Layout

The Reflectarray Layout generation requires to specify an User Function, as detailed in the Reflectarray user guide. The default function is the collimatedBeam that is included in the newFASANT instalation.

Note that the reflectarray functions have no arguments but they can access to internal arguments, as shown in the below figure.

collimatedBeam

collimatedBeam user function for reflectarray layout

6.5.4. Java for beginners

My first user function

Let us look at a simple code that will print the words Hello World. Open the User Functions Editor and add the code as above.

  void myFirstUserFunction() {
    /* 
    This is my first java program. 
    This will print 'Hello World' as the output.
    This is an example of multi-line comments. 
    */ 
    // This is an example of single line comment 
    System.out.println("Hello World"); 
  }

Save the file and try in the Calculator.

  > myFirstUserFunction()

Primitive data types

  • byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.
  • short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.
  • int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.
  • long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigned, divideUnsigned etc to support arithmetic operations for unsigned long.
  • float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.
  • double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
  • boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
  • char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

Basic operations

  • Addition (+): Adds values on either side of the operator.
  • Substraction (-): Substracts right-hand operand from left-hand operand.
  • Multiplication (*): Multiplies values on either side of the operator.
  • Division (/): Divides left-hand operand by right-hand operand.
  • Modulus (%): Divides left-hand operand by right-hand operand and returns remainder.
  • Increment (++): Increases the value of operand by 1.
  • Decrement (--): Decreases the value of operand by 1.

Example:

  void basicOperations(int a, int b, int c, int d) {
    System.out.println("a + b = " + (a + b) );
    System.out.println("a - b = " + (a - b) );
    System.out.println("a * b = " + (a * b) );
    System.out.println("b / a = " + (b / a) );
    System.out.println("b % a = " + (b % a) );
    System.out.println("c % a = " + (c % a) );
    System.out.println("a++ = " + (a++) );
    System.out.println("b-- = " + (a--) );
    
    int f;
    
    // Assign value to 'f'
    f = (a + b) * (c * d);
    System.out.println("f = " + f);
  }

Save the file and try in the Calculator.

  > basicOperations(1, 2, 3, 4)

Relational operations

  • Equal to (==): Checks if the values of two operands are equal or not, if yes then condition becomes true.
  • Not equal to (!=): Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.
  • Greater than (>): Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
  • Less than (<): Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
  • Greater than or equal to(>=): Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
  • Less than or equal to (<=): Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

Example:

  void relationalOperations(int a, int b) {
    System.out.println("a == b = " + (a == b) );
    System.out.println("a != b = " + (a != b) );
    System.out.println("a > b = " + (a > b) );
    System.out.println("a < b = " + (a < b) );
    System.out.println("b >= a = " + (b >= a) );
    System.out.println("b <= a = " + (b <= a) );
  }

Save the file and try in the Calculator.

  > relationalOperations(1, 2)

Logical operations

  • Logical and (&&): Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.
  • Logical or (||): Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true.
  • ! (logical not): Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

Example:

  void logicalOperations() {
    boolean a = true;
    boolean b = false;
    System.out.println("a && b = " + (a && b));
    System.out.println("a || b = " + (a || b) );
    System.out.println("!(a && b) = " + !(a && b));
  }

Save the file and try in the Calculator.

  > logicalOperations()

Advanced operations (Math class)

  • double Math.E: The double value that is closer than any other to e, the base of the natural logarithms.
  • double Math.PI: The double value that is closer than any other to pi, the ratio of the circumference of a circle to its diameter.
  • double Math.abs(double a): Returns the absolute value of a double value.
  • float Math.abs(float a): Returns the absolute value of a float value.
  • int Math.abs(int a): Returns the absolute value of an int value.
  • long Math.abs(long a): Returns the absolute value of a long value.
  • double Math.acos(double a): Returns the arc cosine of a value; the returned angle is in the range 0.0 through pi.
  • int Math.addExact(int x, int y): Returns the sum of its arguments, throwing an exception if the result overflows an int.
  • long Math.addExact(long x, long y): Returns the sum of its arguments, throwing an exception if the result overflows a long.
  • double Math.asin(double a): Returns the arc sine of a value; the returned angle is in the range -pi/2 through pi/2.
  • double Math.atan(double a): Returns the arc tangent of a value; the returned angle is in the range -pi/2 through pi/2.
  • double Math.atan2(double y, double x): Returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta).
  • double Math.cbrt(double a): Returns the cube root of a double value.
  • double Math.ceil(double a): Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.
  • double Math.copySign(double magnitude, double sign): Returns the first floating-point argument with the sign of the second floating-point argument.
  • float Math.copySign(float magnitude, float sign): Returns the first floating-point argument with the sign of the second floating-point argument.
  • double Math.cos(double a): Returns the trigonometric cosine of an angle.
  • double Math.cosh(double x): Returns the hyperbolic cosine of a double value.
  • int Math.decrementExact(int a): Returns the argument decremented by one, throwing an exception if the result overflows an int.
  • long Math.decrementExact(long a): Returns the argument decremented by one, throwing an exception if the result overflows a long.
  • double Math.exp(double a): Returns Euler's number e raised to the power of a double value.
  • double Math.expm1(double x): Returns ex -1.
  • double Math.floor(double a): Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.
  • int Math.floorDiv(int x, int y): Returns the largest (closest to positive infinity) int value that is less than or equal to the algebraic quotient.
  • long Math.floorDiv(long x, long y): Returns the largest (closest to positive infinity) long value that is less than or equal to the algebraic quotient.
  • int Math.floorMod(int x, int y): Returns the floor modulus of the int arguments.
  • long Math.floorMod(long x, long y): Returns the floor modulus of the long arguments.
  • int Math.getExponent(double d): Returns the unbiased exponent used in the representation of a double.
  • int Math.getExponent(float f): Returns the unbiased exponent used in the representation of a float.
  • double Math.hypot(double x, double y): Returns sqrt(x2 +y2) without intermediate overflow or underflow.
  • double Math.IEEEremainder(double f1, double f2): Computes the remainder operation on two arguments as prescribed by the IEEE 754 standard.
  • int Math.incrementExact(int a): Returns the argument incremented by one, throwing an exception if the result overflows an int.
  • long Math.incrementExact(long a): Returns the argument incremented by one, throwing an exception if the result overflows a long.
  • double Math.log(double a): Returns the natural logarithm (base e) of a double value.
  • double Math.log10(double a): Returns the base 10 logarithm of a double value.
  • double Math.log1p(double x): Returns the natural logarithm of the sum of the argument and 1.
  • double Math.max(double a, double b): Returns the greater of two double values.
  • float Math.max(float a, float b): Returns the greater of two float values.
  • int Math.max(int a, int b): Returns the greater of two int values.
  • long Math.max(long a, long b): Returns the greater of two long values.
  • double Math.min(double a, double b): Returns the smaller of two double values.
  • float Math.min(float a, float b): Returns the smaller of two float values.
  • int Math.min(int a, int b): Returns the smaller of two int values.
  • long Math.min(long a, long b): Returns the smaller of two long values.
  • int Math.multiplyExact(int x, int y): Returns the product of the arguments, throwing an exception if the result overflows an int.
  • long Math.multiplyExact(long x, long y): Returns the product of the arguments, throwing an exception if the result overflows a long.
  • int Math.negateExact(int a): Returns the negation of the argument, throwing an exception if the result overflows an int.
  • long Math.negateExact(long a): Returns the negation of the argument, throwing an exception if the result overflows a long.
  • double Math.nextAfter(double start, double direction): Returns the floating-point number adjacent to the first argument in the direction of the second argument.
  • float Math.nextAfter(float start, double direction): Returns the floating-point number adjacent to the first argument in the direction of the second argument.
  • double Math.nextDown(double d): Returns the floating-point value adjacent to d in the direction of negative infinity.
  • float Math.nextDown(float f): Returns the floating-point value adjacent to f in the direction of negative infinity.
  • double Math.nextUp(double d): Returns the floating-point value adjacent to d in the direction of positive infinity.
  • float Math.nextUp(float f): Returns the floating-point value adjacent to f in the direction of positive infinity.
  • double Math.pow(double a, double b): Returns the value of the first argument raised to the power of the second argument.
  • double Math.random(): Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
  • double Math.rint(double a): Returns the double value that is closest in value to the argument and is equal to a mathematical integer.
  • long Math.round(double a): Returns the closest long to the argument, with ties rounding to positive infinity.
  • int Math.round(float a): Returns the closest int to the argument, with ties rounding to positive infinity.
  • double Math.scalb(double d, int scaleFactor): Returns d × 2scaleFactor rounded as if performed by a single correctly rounded floating-point multiply to a member of the double value set.
  • float Math.scalb(float f, int scaleFactor): Returns f × 2scaleFactor rounded as if performed by a single correctly rounded floating-point multiply to a member of the float value set.
  • double Math.signum(double d): Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.
  • float Math.signum(float f): Returns the signum function of the argument; zero if the argument is zero, 1.0f if the argument is greater than zero, -1.0f if the argument is less than zero.
  • double Math.sin(double a): Returns the trigonometric sine of an angle.
  • double Math.sinh(double x): Returns the hyperbolic sine of a double value.
  • double Math.sqrt(double a): Returns the correctly rounded positive square root of a double value.
  • int Math.subtractExact(int x, int y): Returns the difference of the arguments, throwing an exception if the result overflows an int.
  • long Math.subtractExact(long x, long y): Returns the difference of the arguments, throwing an exception if the result overflows a long.
  • double Math.tan(double a): Returns the trigonometric tangent of an angle.
  • double Math.tanh(double x): Returns the hyperbolic tangent of a double value.
  • double Math.toDegrees(double angrad): Converts an angle measured in radians to an approximately equivalent angle measured in degrees.
  • int Math.toIntExact(long value): Returns the value of the long argument; throwing an exception if the value overflows an int.
  • double Math.toRadians(double angdeg): Converts an angle measured in degrees to an approximately equivalent angle measured in radians.
  • double Math.ulp(double d): Returns the size of an ulp of the argument.
  • float Math.ulp(float f): Returns the size of an ulp of the argument.

Example:

  void advancedOperations() {
    System.out.println("toDegrees(pi/2) " + Math.toDegrees(Math.PI/2) );
    System.out.println("sin(pi/2) " + Math.sin(Math.PI/2) );
    System.out.println("cos(pi/2) " + Math.cos(Math.PI/2) );
    System.out.println("2 ^ 0.5 = " + Math.pow(2, 0.5) );
    System.out.println("hypot(1, 1) " + Math.hypot(1, 1) );
  }

Save the file and try in the Calculator.

  > advancedOperations()

Statements

If statement: An if statement consists of a boolean expression followed by one or more statements.

Example:

  void ifExample(int a) {
    if(a % 2 == 0) {
      System.out.println("the value is pair");
    }
  }

Save the file and try in the Calculator.

  > ifExample(2)

If-else statement: An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

Example:

  void ifElseExample(int a) {
    if(a >= 0) {
      System.out.println("the value is positive");
    } else {
      System.out.println("the value is negative");
    }
  }

Save the file and try in the Calculator.

  > ifElseExample(-3)

Loops

While loop: Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

Example:

  void whileExample() {
    int x = 1;
    while(x <= 10) {
      System.out.println("Value of x : " + x );
      x++;
    }
  }

Save the file and try in the Calculator.

  > whileExample()

Do while loop: Like a while statement, except that it tests the condition at the end of the loop body.

Example:

  void doWhileExample() {
    int x = 1;
    do {
      System.out.println("Value of x : " + x );
      x++;
    } while(x <= 10);
  }

Save the file and try in the Calculator.

  > doWhileExample()

For loop: Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

Example:

  void forExample() {
    for(int x = 1; x <= 10; x++) {
      System.out.println("Value of x : " + x );
    }
  }

Save the file and try in the Calculator.

  > forExample()

Arrays

An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference.

  int[] myArray = new int[10];

Alternatively you can create arrays as follows

  int[] myArray = {10, 20, 30, 40};

The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to myArray.length-1.

Example:

  void arrayExample(){
    double[] myArray = {10.1, 60.2, 20.4, 50.4, 30.2, 40.1};
    
    // Print all the array elements
    for (int i = 0; i < myArray.length; i++) {
      System.out.print(" " + myArray[i] + " ");
    }
    System.out.println();
    
    // Summing all elements
    double total = 0;
    for (int i = 0; i < myArray.length; i++) {
      total = total + myArray[i];
    }
    System.out.println("Total is " + total);
    
    // Finding the largest element
    double max = myArray[0];
    for (int i = 1; i < myArray.length; i++) {
      if (myArray[i] > max) {
        max = myArray[i];
      }
    }
    System.out.println("Max is " + max);
  }

Save the file and try in the Calculator.

  > arrayExample()

ArrayList class

The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.

Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.

Example:

  void arrayListExample(){
    // create an array list
    ArrayList myList = new ArrayList();

    // add elements to the array list
    myList.add(1.25);
    myList.add(2.25);
    myList.add(3.25);
    myList.add(4.25);
    myList.add(5.25);
    myList.add(6.25);

    // display the array list
    System.out.println("Size of myList: " + myList.size());
    for(int i=0; i>myList.size(); i++) { 
      System.out.println("Item " + i + " = " + myList.get(i) );
    }
    System.out.println();
    
    // remove elements
    myList.remove(1);
    myList.remove(3);
    
    // display the array list
    System.out.println("Size of myList: " + myList.size());
    for(int i = 0; i > myList.size(); i++) { 
      System.out.println("Item " + i + " = " + myList.get(i) );
    } 
    System.out.println();
  }

Save the file and try in the Calculator.

  > arrayListExample()

HashMap class

The HashMap class uses a hashtable to implement the Map interface. This allows the execution time of basic operations, such as get() and put(), to remain constant even for large sets.

Example:

  double[] generateRandomArray(int size){
    double[] arrayDouble = new double[size];

    for(int i = 0; i < size; i++) {
      arrayDouble[i] = Math.random();	
    }
    return arrayDouble;
  }

  HashMap searchMin(double[] arrayValues){   

    int indexMin = 0;
    double valMin = arrayValues[0];
    for(int i = 1; i < arrayValues.length; i++) {
      if(arrayValues[i] < valMin) {
        valMin = arrayValues[i];
        indexMin = i;
      }
    }

    HashMap map = new HashMap();
    map.put("index", indexMin);
    map.put("value", valMin);
    return map;
  }

  void hashMapExample() {
    // generate a random array
    double[] values = generateRandomArray(10);

    // print array
    System.out.println("Values:");
    for(int i = 0; i < values.length; i++) {
      System.out.println(i + ": " + values[i]);	
    }
    System.out.println();

    // search minimum value and index
    HashMap map = searchMin(values);

    System.out.println("Minimum value: " + map.get("value"));
    System.out.println("Index: " + map.get("index"));
  }

Save the file and try in the Calculator.

  > hashMapExample()

Cmplx class

Cmplx is a class which implements complex numbers in Java. It includes basic operations that can be performed on complex numbers such as, addition, subtraction, multiplication, conjugate, modulus and squaring.

  • Cmplx(double real, double imag): Returns new complex (real,imag).
  • Cmplx(double real): Returns new complex (real, 0).
  • double Cmplx.real(Cmplx c): Returns the real part of a complex value.
  • double Cmplx.imag(Cmplx c): Returns the imaginary part of a complex value.
  • Cmplx Cmplx.conjugate(Cmplx c): Returns the conjugate of a complex value.
  • Cmplx Cmplx.opposite(Cmplx c): Returns the opposite of a complex value.
  • double Cmplx.mod(Cmplx c): Returns the module of a complex value.
  • double Cmplx.abs(Cmplx c): Returns the absoute of a complex value. Corresponds with the module.
  • double Cmplx.phase(Cmplx c): Returns the phase (argument) of a complex value; the returned value is in the range 0 through 360.
  • double Cmplx.arg(Cmplx c): Returns the phase (argument) of a complex value; the returned value is in the range 0 through 2*pi.
  • double Cmplx.argd(Cmplx c): Returns the phase (argument) of a complex value; the returned value is in the range 0 through 360.
  • Cmplx Cmplx.sum(Cmplx c1, Cmplx c2): Returns the sum of two complex values.
  • Cmplx Cmplx.sum(Cmplx c, double d): Returns the sum of complex value by a double value.
  • Cmplx Cmplx.sub(Cmplx c1,Cmplx c2): Returns the subtraction of two complex values.
  • Cmplx Cmplx.sub(Cmplx c, double d): Returns the subtraction of complex value by a double value.
  • Cmplx Cmplx.mul(Cmplx c1, Cmplx c2): Returns the multiplication of two complex values.
  • Cmplx Cmplx.mul(Cmplx c, double d): Returns the multiplication of complex value by a double value.
  • Cmplx Cmplx.div(Cmplx c1, Cmplx c2): Returns the division of two complex values.
  • Cmplx Cmplx.div(Cmplx c, double d): Returns the division of complex value by a double value.
  • Cmplx Cmplx.exp(Cmplx c): Returns Euler's number e raised to the power of a complex value.
  • Cmplx Cmplx.sqrt(Cmplx c): Returns the correctly rounded positive square root of a double value.
  • Cmplx Cmplx.sqrt(Cmplx c): Returns the correctly rounded positive square root of a complex value.
  • double Cmplx.amplitude20(Cmplx c): Returns the amplitude, in db, of a complex value from a lineal magnitude.
  • double Cmplx.amplitude10(Cmplx c): Returns the amplitude, in db, of a complex value from a squared magnitude.
  • double Cmplx.db20(double d): Returns the amplitude, in db, of a module of a complex value from a lineal magnitude.
  • double Cmplx.db10(double d): Returns the amplitude, in db, of a module of a complex value from a squared magnitude.
  • Cmplx Cmplx.nat20(Cmplx c): Returns the complex natural value of a complex value in (dB,degrees) from a lineal magnitude.
  • Cmplx Cmplx.nat10(Cmplx c): Returns the complex natural value of a complex value in (dB,degrees) from a squared magnitude.
  • double Cmplx.idb20(double d): Returns the module of a complex natural value of a value in dB from a lineal magnitude.
  • double Cmplx.idb10(double d): Returns the module of a complex natural value of a value in dB from a squared magnitude.

Example:

  void complexExample(double real, double imag){
    
    Cmplx complex = new Cmplx(real, imag);
    
    System.out.println("Modulus = " + Cmplx.mod(complex));
    System.out.println("Argument (in radians) = " + Cmplx.arg(complex));
    System.out.println("Argument (in degrees) = " + Cmplx.argd(complex));
  }

Save the file and try in the Calculator.

  > complexExample(1, -1)

Import libraries

Files that require any additional library must start with the loading sentence, that is, "import library".

For newFASANT tool, the main libraries that can be required are:

  • java.io: import java.io
  • java.lang: import java.lang
  • java.net: import java.net
  • java.util: import java.util

Further Java information

For more information about the Java language programming you can visit the following external links:

https://docs.oracle.com/javase/tutorial/

https://docs.oracle.com/javase/8/docs/index.html

http://docs.oracle.com/javase/8/docs/api/

We use cookies on this website to improve your navigation experience on this site. By using this site, you agree to our cookie policy.

I agree