banner



How To Change The Sign In Fractions From Denominator To Numerator In Java

Fractions in Coffee

Mathematically, fractions are the parts or sections of values. When an object is broken equally in definite proportions, the value formed is called a fraction. Fractions are classified into Rational and Irrational Numbers.

In the Java programming language, there is a privilege to perform various operations over fractions similar mathematical procedures. One tin add, subtract, multiply, and divide over the fractional numbers.

Below is the code cake that demonstrates the Rational number operations in the user-defined class.

              import java.math.BigInteger; import coffee.util.regex.Matcher; import java.util.regex.Pattern;  public class RationalNumber {     public terminal static RationalNumber Zippo = new RationalNumber(BigInteger.Zip, BigInteger.ONE);      private final BigInteger numerator, denominator;      private RationalNumber(BigInteger numerator, BigInteger denominator) {         this.numerator = numerator;         this.denominator = denominator;     }      private static RationalNumber approved(BigInteger numerator, BigInteger denominator, boolean checkGcd) {         if (denominator.signum() == 0) {             throw new IllegalArgumentException("denominator is aught");         }         if (numerator.signum() == 0) {             return Naught;         }         if (denominator.signum() < 0) {             numerator = numerator.negate();             denominator = denominator.negate();         }         if (checkGcd) {             BigInteger gcd = numerator.gcd(denominator);             if (!gcd.equals(BigInteger.ONE)) {                 numerator = numerator.divide(gcd);                 denominator = denominator.carve up(gcd);             }         }         return new RationalNumber(numerator, denominator);     }      public static RationalNumber getInstance(long numerator, long denominator) {         return canonical(new BigInteger("" + numerator), new BigInteger("" + denominator), true);     }      public static RationalNumber valueOf(String s) {         Pattern p = Blueprint.compile("(-?\\d+)(?:.(\\d+)?)?0*(?:eastward(-?\\d+))?");         Matcher m = p.matcher(s);         if (!m.matches()) {             throw new IllegalArgumentException("Unknown format '" + s + "'");         }         String whole = m.group(1);         Cord decimal = thou.grouping(ii);         Cord exponent = one thousand.group(3);         Cord n = whole;         if (decimal != nada) {             north += decimal;         }         BigInteger numerator = new BigInteger(n);         int exp = exponent == naught ? 0 : Integer.valueOf(exponent);         int decimalPlaces = decimal == goose egg ? 0 : decimal.length();         exp -= decimalPlaces;         BigInteger denominator;         if (exp < 0) {             denominator = BigInteger.X.prisoner of war(-exp);         } else {             numerator = numerator.multiply(BigInteger.TEN.prisoner of war(exp));             denominator = BigInteger.I;         }          return approved(numerator, denominator, truthful);     }      public static void master(String[] args) {         RationalNumber r1 = RationalNumber.valueOf("3.14e4");         RationalNumber r2 = RationalNumber.getInstance(111, 7);         convert("r1", r1);         convert("r2", r2);         convert("r1 + r2", r1.add together(r2));         convert("r1 - r2", r1.subtract(r2));         catechumen("r1 * r2", r1.multiply(r2));         convert("r1 / r2", r1.divide(r2));         convert("r2 ^ 2", r2.pw(2));     }      public static void convert(String name, RationalNumber r) {         System.out.printf("%s = %s%n", name, r);         System.out.printf("%due south.negate() = %south%n", proper name, r.negate());         Organisation.out.printf("%due south.invert() = %s%n", name, r.invert());         Organisation.out.printf("%s.intValue() = %,d%n", name, r.intValue());         Arrangement.out.printf("%due south.longValue() = %,d%n", name, r.longValue());         Arrangement.out.printf("%south.floatValue() = %,f%n", name, r.floatValue());         System.out.printf("%s.doubleValue() = %,f%n", proper noun, r.doubleValue());         System.out.println();     }      public RationalNumber add(RationalNumber o) {         if (o.numerator.signum() == 0) {             return this;         } else if (numerator.signum() == 0) {             render o;         } else if (denominator.equals(o.denominator)) {             return new RationalNumber(numerator.add together(o.numerator), denominator);         } else {             return approved(numerator.multiply(o.denominator).add(o.numerator.multiply(denominator)), denominator.multiply(o.denominator), truthful);         }     }      public RationalNumber multiply(RationalNumber o) {         if (numerator.signum() == 0 || o.numerator.signum() == 0) {             return ZERO;         } else if (numerator.equals(o.denominator)) {             return canonical(o.numerator, denominator, true);         } else if (o.numerator.equals(denominator)) {             return canonical(numerator, o.denominator, true);         } else if (numerator.negate().equals(o.denominator)) {             return canonical(o.numerator.negate(), denominator, true);         } else if (o.numerator.negate().equals(denominator)) {             return canonical(numerator.negate(), o.denominator, truthful);         } else {             return canonical(numerator.multiply(o.numerator), denominator.multiply(o.denominator), true);         }     }      public boolean isInteger() {         render numerator.signum() == 0 || denominator.equals(BigInteger.I);     }      public RationalNumber negate() {         return new RationalNumber(numerator.negate(), denominator);     }      public RationalNumber invert() {         return approved(denominator, numerator, false);     }      public RationalNumber pow(int exp) {         render canonical(numerator.pow(exp), denominator.prisoner of war(exp), true);     }      public RationalNumber subtract(RationalNumber o) {         return add together(o.negate());     }      public RationalNumber dissever(RationalNumber o) {         return multiply(o.invert());     }      public int intValue() {         return isInteger() ? numerator.intValue() : numerator.divide(denominator).intValue();     }      public long longValue() {         render isInteger() ? numerator.longValue() : numerator.carve up(denominator).longValue();     }      public float floatValue() {         render (float) doubleValue();     }      public double doubleValue() {         return isInteger() ? numerator.doubleValue() : numerator.doubleValue() / denominator.doubleValue();     }      @Override     public String toString() {         return isInteger() ? String.format("%,d", numerator) : String.format("%,d / %,d", numerator, denominator);     } }                          

In the programme above, the execution starts from the master method. Firstly, a rational number gets initialized using the static valueOf() role defined in the grade. It takes a string value and performs manipulations over the input Cord.

It returns a RationalNumber of the user-defined type. The function first checks for an input Cord with proper validations and patterns. The input String gets separated into exponent, decimal, and the whole function. These individual cleaved values combine to form a rational number.

Another way of creating a rational number is using an instanceOf() static mill role. The method internally calls the canonical function, which calls a private constructor of the class. The constructor separates and sets the values of the numerator and denominator for a specific case. Past canonical course, information technology merely ways the standard representation grade of the rational number.

In the given instance, p/q is the standard or canonical class where q!=0 should always be true. The method has the logic written to satisfy the basic atmospheric condition of a rational number. Information technology checks for the sign of numerator and denominator separately and performs operations. It checks for denominator values; if it's zero, the operation throws an exception. It also checks for the greatest common divisor or gcd in the numerator and denominator values. The gcd office is present in the BigInteger class that returns a BigInteger value.

Moving ahead, the convert method gets called, passing the first rational number instance that gets created. This method too calls upon seven dissimilar functions over the rational number instance that gets passed.

Below, y'all'll sympathise each of these methods better:

  • Print the rational number in the print stream. Generally, whenever an instance gets printed, the default toString method gets chosen. The method prints the name of the class followed past the hexadecimal representation of the memory location. But here, the office is overridden to give some other implementation that represents the number in the p/q form.
  • The negate function will internally negate the rational number by calling the negate method of the BigInteger class. Information technology will add a minus sign earlier the rational number.
  • The capsize function internally calls the canonical method with a single difference. It internally passes the third checkGcd parameter as false. When the input value is Boolean true, the method logic simplifies the rational number by dividing the fraction by its greatest common divisor. But in this case, the need is to invert without simplification.
  • The intValue function beginning checks if the instance is an Integer value. Integers are numbers that can be positive, negative, or naught but cannot exist fractions. So, internally it calls the divide method over numerator and denominator. The method is given in the BigInteger class and returns a BigInteger value. It besides throws ArithmeticException when the denominator finds a nil value. The returned value gets transformed into an int value using intValue part.
  • The longValue role internally calls the split part snd parse the BigInteger output to a long datatype.
  • The floatValue function provides the floating-point value of the rational number. And and then every bit the doubleValue() part, which typecasts the output in the Double datatype.

The whole process gets chosen upon an initial rational number instance that is the r1 case. A like sequence is again repeated and gets printed for rational example r2.

Mathematical Operations for Fractions in Java

Now add, decrease, divide, multiply, and power arithmetic operations need two operands for evaluation. So permit's discuss the methods in item beneath:

  1. The add together function starting time checks for the numerator values if they are positive, negative, or zero. If non-nil, it checks if the denominators of both the rational number are the same. If plant the same, it adds the numerator value and returns the rational number formed. Else if not establish similar, it defines logic for rational number addition.
  2. The decrease method internally calls the add together method later on negating the second rational number case passed.
  3. The multiply method has quite a complex logic internally. It checks if the numerator is nil of either of the rational number, it returns the output as a zero value. If non nil, it checks the numerator with the denominator of either set. That is the r1 numerator gets checked with the r2 denominator and vice-versa. When no status matches, the numerator of r1 gets multiplied to r2 instance numerator, and the denominators of both go multiplied. Finally, information technology calls the multiply function of the BigInteger class to perform multiplication.
  4. The divide function will invert the passed example and internally phone call the multiply function using the start instance.
  5. Last is the pow role which evaluates the second power of the r2 instance. The implementation of pow gets defined in the BigInteger class that takes the exponent for evaluation. The method throws the ArithmeticException exception when the exponent is a negative value.

Below is the output of the circuitous code given above:

              r1 = 31,400 r1.negate() = -31,400 r1.invert() = 1 / 31,400 r1.intValue() = 31,400 r1.longValue() = 31,400 r1.floatValue() = 31,400.000000 r1.doubleValue() = 31,400.000000  r2 = 111 / seven r2.negate() = -111 / 7 r2.invert() = seven / 111 r2.intValue() = fifteen r2.longValue() = 15 r2.floatValue() = 15.857142 r2.doubleValue() = 15.857143  r1 + r2 = 219,911 / 7 r1 + r2.negate() = -219,911 / 7 r1 + r2.invert() = 7 / 219,911 r1 + r2.intValue() = 31,415 r1 + r2.longValue() = 31,415 r1 + r2.floatValue() = 31,415.857422 r1 + r2.doubleValue() = 31,415.857143  r1 - r2 = 219,689 / 7 r1 - r2.negate() = -219,689 / 7 r1 - r2.invert() = 7 / 219,689 r1 - r2.intValue() = 31,384 r1 - r2.longValue() = 31,384 r1 - r2.floatValue() = 31,384.142578 r1 - r2.doubleValue() = 31,384.142857  r1 * r2 = three,485,400 / 7 r1 * r2.negate() = -3,485,400 / 7 r1 * r2.invert() = 7 / 3,485,400 r1 * r2.intValue() = 497,914 r1 * r2.longValue() = 497,914 r1 * r2.floatValue() = 497,914.281250 r1 * r2.doubleValue() = 497,914.285714  r1 / r2 = 219,800 / 111 r1 / r2.negate() = -219,800 / 111 r1 / r2.invert() = 111 / 219,800 r1 / r2.intValue() = i,980 r1 / r2.longValue() = 1,980 r1 / r2.floatValue() = 1,980.180176 r1 / r2.doubleValue() = 1,980.180180  r2 ^ 2 = 12,321 / 49 r2 ^ two.negate() = -12,321 / 49 r2 ^ 2.invert() = 49 / 12,321 r2 ^ 2.intValue() = 251 r2 ^ 2.longValue() = 251 r2 ^ two.floatValue() = 251.448975 r2 ^ two.doubleValue() = 251.448980                          

Write for the states

DelftStack articles are written by software geeks like you lot. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us folio.

Related Commodity - Java Math

  • Summate Median of an Assortment in Java
  • Pascal'south Triangle in Java
  • Calculate Logarithm in Java
  • Method to Calculate Factorial in Java
  • Ezoic

    Source: https://www.delftstack.com/howto/java/fractions-in-java/

    Posted by: leverettfainizind.blogspot.com

    0 Response to "How To Change The Sign In Fractions From Denominator To Numerator In Java"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel