JavaJava · Chapterبەش 4 · Lectureوانە 4.5

The Math Classکلاسەکەی Math

Java's Math class: static methods called with the class name, max and min, sqrt, cbrt and pow, abs, rounding with round, floor, ceil and rint (and the types they return), random numbers with Math.random() and why Random and ThreadLocalRandom exist, Math.PI and Math.E, hypot, the overflow-safe Exact methods, and import static.

Mathـی Java: کە بە ناوی بانگ دەکرێن، max و min، sqrt، cbrt و pow، abs، بە round، floor، ceil و rint (و ئەو جۆرانەی دەیگەڕێننەوە)، بە Math.random() و بۆچی Random و ThreadLocalRandom هەن، Math.PI و Math.E، hypot، Exact کە ناهێڵن و import static.

13 min read12 خولەک خوێندنەوە · 18 stepsهەنگاو

What you will learnچی فێر دەبیت

  • Call static methods of Math with arguments, and use their return values.
  • Choose the right method for powers, roots, absolute values and each kind of rounding, and know what type it returns.
  • Make random whole numbers in a range, and know when Random, a seed or SecureRandom is needed.
  • Math بە بانگ بکەیت و بەکار بهێنیت.
  • گونجاو بۆ توان، ڕەگ، و هەر جۆرێکی هەڵبژێریت و بزانیت چ جۆرێک دەگەڕێنێتەوە.
  • هەڕەمەکی لە نێوان دوو سنووردا دروست بکەیت و بزانیت کەی Random، یان SecureRandom پێویستە.

Math: a class full of ready methodsMath: کلاسێک پڕ لە میتۆدی ئامادە

Java's Math class holds ready-made methods for mathematical jobs: maximum and minimum, powers, roots, rounding, random numbers and more, plus the constants π and e. All of them are : they belong to the class itself, so you call them with the class name and a dot, Math.sqrt(64), without creating an object. Math is in the package java.lang, which every Java program can use without an import (java.lang). Static members and object members are compared in static members and instance members.

Mathـی Java ئامادەی تێدایە بۆ کاری بیرکاری: گەورەترین و بچووکترین، توان، ڕەگ، ، و زیاتر، لەگەڵ π و e. هەموویان : هی خودی ، بۆیە بە ناوی و خاڵێک بانگیان دەکەیت، Math.sqrt(64)، بەبێ دروستکردنی . Math لە java.langـدایە، کە هەموو Java بەبێ import دەتوانێت بەکاری بهێنێت (⁦java.lang⁩). جیاوازیی و ئەندامەکانی لە ئەندامە ستاتیکەکان و ئەندامەکانی ئۆبجێکتـدا ڕوون کراوەتەوە.

An open toolbox labelled Math, from java.lang. Its tools are labels: max, min, abs, sqrt, cbrt, pow, round, floor, ceil, random, hypot and addExact, and two constants, PI and E. Note: use a tool with the class name in front, Math.sqrt(9); no import and no new.سندووقێکی ئامرازی کراوە بە ناوی Math، لە java.lang. ئامرازەکانی ناونیشانن: max، min، abs، sqrt، cbrt، pow، round، floor، ceil، random، hypot و addExact و دوو نەگۆڕ، PI و E. تێبینی: ئامرازێک بە ناوی کلاسەکە لە پێشیەوە بەکار بهێنە، Math.sqrt(9)؛ نە import، نە new.
The Math class: a toolbox of static methods Math: سندووقێکی ئامرازی CêIT

Python keeps the same tools in its math module (More maths), and MATLAB has them built in (Maths functions).

Python هەمان ئامرازەکان لە مۆدیوڵی mathـدا هەڵدەگرێت (بیرکاریی زیاتر) و MATLAB لە خۆیدا هەیەتی (کردارەکانی بیرکاری).

Math: a class full of ready methodsMath: کلاسێک پڕ لە میتۆدی ئامادە

Calling a Math methodبانگکردنی میتۆدێکی Math

A call has the class, a dot, the method's name and the in brackets. The method does its work and gives back a , which you can print, store in a variable or use in a bigger expression: double side = Math.sqrt(area);.

بانگکردنێک لە ، خاڵێک، ناوی و لە ناو کەوانەدا پێک دێت. کارەکەی دەکات و دەگەڕێنێتەوە، کە دەتوانیت چاپی بکەیت، لە هەڵیبگریت یان لە گەورەتردا بەکاری بهێنیت: double side = Math.sqrt(area);.

Top: Math.sqrt(9) with its parts named: Math is the class, sqrt the method, 9 the argument. Below, three machines: 9 goes into Math.sqrt and 3.0 comes out; 9 and 3 go into Math.max and 9 comes out; 2 and 10 go into Math.pow and 1024.0 comes out.سەرەوە: Math.sqrt(9) بە ناوی بەشەکانییەوە: Math کلاسەکەیە، sqrt میتۆدەکە، 9 ئارگیومێنتەکە. لە خوارەوە سێ ئامێر: 9 دەچێتە ناو Math.sqrt و 3.0 دێتە دەرەوە؛ 9 و 3 دەچنە ناو Math.max و 9 دێتە دەرەوە؛ 2 و 10 دەچنە ناو Math.pow و 1024.0 دێتە دەرەوە.
Arguments go in, a return value comes out دەچنە ژوورەوە، دێتە دەرەوەCêIT

Math.max and Math.min⁦Math.max⁩ و ⁦Math.min⁩

Math.max(x, y) returns the bigger of two numbers and Math.min(x, y) the smaller one:

Math.max(x, y) گەورەترینی دوو ژمارە دەگەڕێنێتەوە و Math.min(x, y) بچووکترینیان:

MinMaxNo.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class MinMaxNo {
    public static void main(String[] args) {
        int firstNo = 9, secondNo = 3;
        int minNo = Math.min(firstNo, secondNo);
        System.out.println("The minimum number is: " + minNo);
        int maxNo = Math.max(firstNo, secondNo);
        System.out.println("The maximum number is: " + maxNo);
    }
}
A number line from -25 to 15. max(9, 3) = 9 marks 9, the one further right; min(9, 3) = 3 marks 3. max(-10, -20) = -10 marks -10; min(-10, -20) = -20 marks -20. Note: with negative numbers, the bigger one is the one closer to 0.هێڵی ژمارەکان لە -25 تا 15. max(9, 3) = 9 نیشانە لە 9 دەدات، ئەوەی زیاتر لای ڕاستە؛ min(9, 3) = 3 نیشانە لە 3. max(-10, -20) = -10 نیشانە لە -10 دەدات؛ min(-10, -20) = -20 لە -20. تێبینی: لە ژمارەی نەرێنیدا، گەورەترەکە ئەوەیە نزیکترە لە 0.
max is further right, min further leftmax زیاتر لای ڕاستە، min زیاتر لای چەپCêIT

There are versions for int, long, float and double: one name, several parameter types (, see How Java chooses a version). With mixed types the int is widened: Math.max(2.5, 3) is 3.0. For the largest of three, nest the calls: Math.max(4, Math.max(9, 7)) is 9.

وەشانی جیاواز بۆ int، long، float و double هەیە: یەک ناو و چەند جۆرێکی (، بڕوانە Java چۆن وەشانێک هەڵدەبژێرێت). بە تێکەڵکردنی جۆرەکان int دەبێتە double: Math.max(2.5, 3) دەکاتە ⁦3.0⁩. بۆ گەورەترینی سێ ژمارە، بانگکردنەکان لە ناو یەکتردا بنووسە: Math.max(4, Math.max(9, 7)) دەکاتە 9.

Square roots and cube rootsڕەگی دووجا و ڕەگی سێجا

Math.sqrt(x) returns the and Math.cbrt(x) the , both always as a double (Powers, roots and absolute value):

Math.sqrt(x) دەگەڕێنێتەوە و Math.cbrt(x) ، هەردووکیان هەمیشە وەک double (توان، ڕەگ و نرخی ڕووت):

SquareRoot.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class SquareRoot {
    public static void main(String[] args) {
        int firstNo = 3, secondNo = 9;
        double squareRoot1 = Math.sqrt(firstNo);
        double squareRoot2 = Math.sqrt(secondNo);
        System.out.println("The square root of No1 is: " + squareRoot1
                + "\nThe square root of No2 is: " + squareRoot2);
    }
}
Left: a square made of 3 by 3 small squares, area 9, side 3: Math.sqrt(9) = 3.0. Right: a cube made of 3 by 3 by 3 small cubes, volume 27, edge 3: Math.cbrt(27) = 3.0. Note: both return a double; Math.sqrt(-1) is NaN and Math.cbrt(-8) is -2.0.چەپ: چوارگۆشەیەک لە 3 لە 3 چوارگۆشەی بچووک، ڕووبەر 9، لا 3: Math.sqrt(9) = 3.0. ڕاست: سێجایەک لە 3 لە 3 لە 3 سێجای بچووک، قەبارە 27، لێوار 3: Math.cbrt(27) = 3.0. تێبینی: هەردووکیان double دەگەڕێننەوە؛ Math.sqrt(-1) دەبێتە NaN و Math.cbrt(-8) دەبێتە -2.0.
sqrt finds the side, cbrt the edgesqrt لای چوارگۆشە دەدۆزێتەوە، cbrt لێواری سێجاCêIT

A negative number has no real square root, so Math.sqrt(-1) is NaN (Infinity and NaN). A cube root works for negatives: Math.cbrt(-8) is -2.0.

ژمارەی نەرێنی ڕاستەقینەی نییە، بۆیە Math.sqrt(-1) دەبێتە NaN (Infinity و NaN). بۆ ژمارەی نەرێنیش کار دەکات: Math.cbrt(-8) دەکاتە -2.0.

Powers: Math.powبەرزکردنەوە بۆ توان: ⁦Math.pow⁩

Java has no power operator. Math.pow(x, y) gives x to the power y, xyx^{y}, always as a double, such as x4x^{4} with Math.pow(x, 4). A fraction as the power gives a root: Math.pow(9, 0.5) is 3.0.

Java نییە. Math.pow(x, y) x بە توانی y دەدات، xyx^{y}، هەمیشە وەک double، وەک x4x^{4} بە Math.pow(x, 4). وەک ڕەگ دەدات: Math.pow(9, 0.5) دەکاتە ⁦3.0⁩.

Power.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Power {
    public static void main(String[] args) {
        System.out.println(Math.pow(2, 10));
        System.out.println(Math.pow(2, 8));
        System.out.println(Math.pow(9, 0.5));     // a square root
        System.out.println(Math.pow(2, -1));
        System.out.println(Math.pow(5, 0));
        long big = (long) Math.pow(2, 40);         // a whole number again
        System.out.println(big);
        System.out.println(2 ^ 10);               // NOT a power
    }
}
Left card, tick: Math.pow(2, 10) is 2 × 2 × … × 2, ten times, = 1024.0, always a double. Right card, cross: 2 ^ 10 compares the bits 0010 and 1010 and gives 1000 = 8: ^ is XOR, not a power.کارتی چەپ، ڕاستە: Math.pow(2, 10) واتە 2 × 2 × … × 2، دە جار، = 1024.0، هەمیشە double. کارتی ڕاست، هەڵەیە: 2 ^ 10 بیتەکانی 0010 و 1010 بەراورد دەکات و 1000 = 8 دەدات: ^ بریتییە لە XOR، نەک بەرزکردنەوە بۆ توان.
Math.pow, not ^⁦Math.pow⁩، نەک ^CêIT

Absolute value: Math.absنرخی ڕووت: ⁦Math.abs⁩

Math.abs(x) gives the : the distance from 0, never negative. It keeps the type: Math.abs(-5) is the int 5 and Math.abs(-4.7) the double 4.7. Math.abs(a - b) is the distance between two numbers, whichever is bigger.

Math.abs(x) دەدات: دووری لە 0، هەرگیز نەرێنی نییە. جۆرەکە دەپارێزێت: Math.abs(-5) intـی 5ـە و Math.abs(-4.7) doubleـی ⁦4.7⁩. Math.abs(a - b) دووریی نێوان دوو ژمارەیە، هەرکامیان گەورەتر بێت.

Absolute.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Absolute {
    public static void main(String[] args) {
        System.out.println(Math.abs(-4.7));
        System.out.println(Math.abs(5));
        System.out.println(Math.abs(-5));
        int a = 3, b = 10;
        System.out.println(Math.abs(a - b));      // the distance between a and b
    }
}
Top: a number line from -6 to 6 where -4.7 and 4.7 are the same distance, 4.7, from 0: Math.abs(-4.7) = 4.7. Bottom: a number line from 0 to 12 with a bar from 3 to 10: Math.abs(3 - 10) = 7.سەرەوە: هێڵی ژمارەکان لە -6 تا 6 کە -4.7 و 4.7 هەمان دوورییان لە 0 هەیە، 4.7: Math.abs(-4.7) = 4.7. خوارەوە: هێڵی ژمارەکان لە 0 تا 12 بە هێڵێک لە 3 تا 10: Math.abs(3 - 10) = 7.
The distance from 0, or between two numbersدووری لە 0، یان لە نێوان دوو ژمارەداCêIT

Rounding: round, floor, ceil and rintنزیککردنەوە: round، floor، ceil و rint

Four methods turn a decimal number into a whole number, each in its own way. Math.round goes to the nearest whole number, and a half goes up, toward positive infinity: 2.5 becomes 3 and -2.5 becomes -2 (). Math.floor always goes down () and Math.ceil always up (). Math.rint goes to the nearest, but sends a half to the even neighbour (): 4.5 becomes 4.0.

چوار ژمارەی دەیی دەکەن بە ، هەریەکە بە شێوەی خۆی. Math.round دەچێت بۆ نزیکترین و نیوە بەرەو سەرەوە دەچێت، بەرەو ئەرێنی: ⁦2.5⁩ دەبێتە 3 و -2.5 دەبێتە -2 (). Math.floor هەمیشە بەرەو خوار دەچێت () و Math.ceil هەمیشە بەرەو سەرەوە (). Math.rint دەچێت بۆ نزیکترین، بەڵام نیوە دەنێرێت بۆ دراوسێ جووتەکە (): ⁦4.5⁩ دەبێتە ⁦4.0⁩.

Rounding.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Rounding {
    public static void main(String[] args) {
        System.out.println(Math.round(4.1) + " " + Math.round(4.5) + " " + Math.round(4.9) + " " + Math.round(-2.5));
        System.out.println(Math.floor(4.1) + " " + Math.floor(4.5) + " " + Math.floor(4.9) + " " + Math.floor(-2.5));
        System.out.println(Math.ceil(4.1) + " " + Math.ceil(4.5) + " " + Math.ceil(4.9) + " " + Math.ceil(-2.5));
        System.out.println(Math.rint(4.1) + " " + Math.rint(4.5) + " " + Math.rint(4.9) + " " + Math.rint(-2.5));
    }
}
Number lines with 4.1, 4.5 and 4.9 between 4 and 5, and -2.5 between -3 and -2. A table: Math.round gives 4, 5, 5, -2 (a long; nearest, a half goes up). Math.floor gives 4.0, 4.0, 4.0, -3.0 (a double; always down). Math.ceil gives 5.0, 5.0, 5.0, -2.0 (always up). Math.rint gives 4.0, 4.0, 5.0, -2.0 (nearest, a half goes to even).هێڵەکانی ژمارەکان بە 4.1، 4.5 و 4.9 لە نێوان 4 و 5 و -2.5 لە نێوان -3 و -2. خشتەیەک: Math.round دەدات 4، 5، 5، -2 (long؛ نزیکترین، نیوە بەرەو سەرەوە). Math.floor دەدات 4.0، 4.0، 4.0، -3.0 (double؛ هەمیشە بەرەو خوار). Math.ceil دەدات 5.0، 5.0، 5.0، -2.0 (هەمیشە بەرەو سەرەوە). Math.rint دەدات 4.0، 4.0، 5.0، -2.0 (نزیکترین، نیوە بەرەو جووت).
Four ways to a whole numberچوار ڕێگە بۆ CêIT

Rounding: round, floor, ceil and rintنزیککردنەوە: round، floor، ceil و rint

What type comes back?چ جۆرێک دەگەڕێتەوە؟

Math.round returns a long for a double and an int for a float; floor, ceil and rint return a double such as 7.0. So int r = Math.round(2.7); does not compile: incompatible types: possible lossy conversion from long to int. Write long r = …, or int r = (int) Math.round(2.7); (Narrowing).

Math.round بۆ double جۆری long دەگەڕێنێتەوە و بۆ float جۆری int؛ floor، ceil و rint doubleـێک وەک ⁦7.0⁩ دەگەڕێننەوە. بۆیە int r = Math.round(2.7); کۆمپایل نابێت: incompatible types: possible lossy conversion from long to int. بنووسە long r = …، یان int r = (int) Math.round(2.7); (تەسککردنەوەی جۆر).

RoundTypes.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class RoundTypes {
    public static void main(String[] args) {
        long a = Math.round(36.4);       // a double gives a long
        int b = Math.round(2.7f);        // a float gives an int
        double c = Math.floor(7.9);      // floor, ceil and rint give a double
        System.out.println(a + " " + b + " " + c);
    }
}

To round to two decimal places, multiply by 100, round, and divide by 100.0: Math.round(2.345 * 100) / 100.0 is 2.35, and the lab's 36172.799999999996 becomes 36172.8. For printing, printf("%.2f", x) is easier (Two decimal places, rounded).

بۆ بۆ دوو ، لە ⁦100⁩ لێکی بدە، نزیکی بکەرەوە و دابەشی بکە بەسەر ⁦100.0⁩: Math.round(2.345 * 100) / 100.0 دەکاتە ⁦2.35⁩ و ⁦36172.799999999996⁩ـی تاقیگەکە دەبێتە ⁦36172.8⁩. بۆ چاپکردن، printf("%.2f", x) ئاسانترە (دوو خانەی دەیی، نزیککراوە).

TwoPlaces.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class TwoPlaces {
    public static void main(String[] args) {
        double volume = 36172.799999999996;
        System.out.println(Math.round(volume * 100) / 100.0);
        double price = 2.345;
        System.out.println(Math.round(price * 100) / 100.0);
    }
}

Random numbers: Math.randomژمارە هەڕەمەکییەکان: ⁦Math.random⁩

Math.random() returns a : a double from 0.0 up to, but not including, 1.0. Scale it to the range you need. For a die (1 to 6): multiply by 6 (0.0 up to 6.0), cut off the fraction with (int) (0 to 5), then add 1:

Math.random() دەگەڕێنێتەوە: doubleـێک لە ⁦0.0⁩ تا کەمتر لە ⁦1.0⁩. بیگۆڕە بۆ ئەو سنوورانەی دەتەوێت. بۆ زارێک (⁦1⁩ تا ⁦6⁩): لە 6 لێکی بدە (⁦0.0⁩ تا کەمتر لە ⁦6.0⁩)، بە (int) ببڕەوە (⁦0⁩ تا ⁦5⁩)، پاشان 1 زیاد بکە:

Animation. Math.random() gives 0.7318…, a point between 0 and 1. Times 6 gives 4.3908…, between 0 and 6. (int) cuts off the fraction: 4, one of 0 to 5. Plus 1 gives 5, one of 1 to 6. The last frame shows a die with five dots: you rolled a 5; run it again for a new number.
Animation. Math.random() gives 0.7318…, a point between 0 and 1. Times 6 gives 4.3908…, between 0 and 6. (int) cuts off the fraction: 4, one of 0 to 5. Plus 1 gives 5, one of 1 to 6. The last frame shows a die with five dots: you rolled a 5; run it again for a new number.
From Math.random() to a dieلە ⁦Math.random()⁩ـەوە بۆ زارCêIT
Dice.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Dice {
    public static void main(String[] args) {
        double r = Math.random();                   // 0.0 up to, but not including, 1.0
        System.out.println(r);
        int die = (int) (Math.random() * 6) + 1;    // a whole number from 1 to 6
        System.out.println("You rolled " + die);
    }
}

Random numbers: Math.randomژمارە هەڕەمەکییەکان: ⁦Math.random⁩

More control: Random and ThreadLocalRandomکۆنترۆڵی زیاتر: Random و ThreadLocalRandom

Behind Math.random() is one shared java.util.Random object. Make your own Random when you need more (import java.util.Random; and new Random(…) work like the Scanner lines in Two lines get a Scanner ready): nextInt(1, 7) gives a whole number from 1 to 6 directly (Java 17), and a fixed repeats the same sequence every run, which makes tests repeatable:

لە پشت Math.random()ـەوە یەک هاوبەشی java.util.Random هەیە. ئەگەر زیاترت دەوێت، Randomـی خۆت دروست بکە (import java.util.Random; و new Random(…) وەک دێڕەکانی Scanner کار دەکەن لە دوو دێڕ Scanner ئامادە دەکەن): nextInt(1, 7) ڕاستەوخۆ لە 1 تا 6 دەدات ⁦(Java 17)⁩ و جێگیر هەمان زنجیرە لە هەموو جێبەجێکردنێکدا دووپاتە دەکاتەوە، کە تاقیکردنەوە دووپاتەکراوە دەکات:

SeededDice.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Random;

public class SeededDice {
    public static void main(String[] args) {
        Random rng = new Random(42);          // the seed 42: the same rolls every time
        System.out.println(rng.nextInt(1, 7));
        System.out.println(rng.nextInt(1, 7));
        System.out.println(rng.nextInt(1, 7));
    }
}
Three rows. new Random(42), run 1: dice 3, 4, 1. new Random(42), run 2: dice 3, 4, 1 again. Math.random(): different dice every run, with a question mark.سێ ڕیز. new Random(42)، جاری یەکەم: زارەکانی 3، 4، 1. new Random(42)، جاری دووەم: دیسان 3، 4، 1. Math.random(): هەر جارێک زاری جیاواز، لەگەڵ نیشانەی پرسیار.
The same seed repeats the same numbersهەمان هەمان ژمارەکان دووپاتە دەکاتەوەCêIT

Programs that do many jobs at the same time (threads) use ThreadLocalRandom.current().nextInt(1, 7), so they do not wait for one shared generator. None of these is safe for passwords or secret codes: use java.security.SecureRandom (Cryptography basics).

کە چەند کارێک لە یەک کاتدا دەکات (threads) ThreadLocalRandom.current().nextInt(1, 7) بەکار دەهێنێت، بۆ ئەوەی چاوەڕێی یەک بەرهەمهێنەری هاوبەش نەکات. هیچکامیان بۆ یان کۆدی نهێنی سەلامەت نین: java.security.SecureRandom بەکار بهێنە (بنەماکانی کریپتۆگرافی).

Math.PI and Math.E⁦Math.PI⁩ و ⁦Math.E⁩

Math.PI (π, about 3.14159) and Math.E (, about 2.71828) are constants: static final double values in the Math class (Constants). Use them instead of typing 3.14, which is less exact:

Math.PI (π، نزیکەی ⁦3.14159⁩) و Math.E (، نزیکەی ⁦2.71828⁩) : static final double لە Mathـدا (نەگۆڕەکان). لە جیاتی نووسینی ⁦3.14⁩ بەکاریان بهێنە، کە کەمتر وردە:

Circle.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Circle {
    public static void main(String[] args) {
        double r = 3;
        System.out.println(Math.PI);
        System.out.println(Math.E);
        System.out.println(Math.PI * r * r);      // the area of a circle
        System.out.println(2 * Math.PI * r);      // the distance round it
    }
}
A circle with radius r = 3. Beside it: area = π r², Math.PI * r * r = 28.274333882308138; around = 2 π r, 2 * Math.PI * r = 18.84955592153876. Below: Math.PI = 3.141592653589793.بازنەیەک بە نیوەتیرەی r = 3. لە تەنیشتیەوە: ڕووبەر = π r²، Math.PI * r * r = 28.274333882308138؛ چێوە = 2 π r، 2 * Math.PI * r = 18.84955592153876. لە خوارەوە: Math.PI = 3.141592653589793.
A circle with Math.PIبازنەیەک بە ⁦Math.PI⁩CêIT

With 3.14, the first water tank of the lab holds 52987.5; with Math.PI it is 53014.37602932776.

بە ⁦3.14⁩، یەکەم تانکی ئاوی تاقیگەکە ⁦52987.5⁩ هەڵدەگرێت؛ بە Math.PI دەبێتە ⁦53014.37602932776⁩.

Math.hypot: the long side⁦Math.hypot⁩: درێژترین لا

Math.hypot(x, y) gives x2+y2\sqrt{x^{2} + y^{2}}: the long side of a right triangle with sides x and y, or the distance between two points. For sides 3 and 4 it is 5.0. It is safer than typing the formula, because it never overflows in the middle of the calculation:

Math.hypot(x, y) x2+y2\sqrt{x^{2} + y^{2}} دەدات: درێژترین لای سێگۆشەیەکی ڕاستگۆشە بە لاکانی x و y، یان دووریی نێوان دوو خاڵ. بۆ لاکانی 3 و 4 دەکاتە ⁦5.0⁩. لە نووسینی فۆرمولەکە سەلامەترە، چونکە لە ناوەڕاستی ژماردندا هەرگیز نابێت:

Hypotenuse.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Hypotenuse {
    public static void main(String[] args) {
        System.out.println(Math.hypot(3, 4));
        System.out.println(Math.sqrt(3 * 3 + 4 * 4));
        double big = 1e200;
        System.out.println(Math.hypot(big, big));
        System.out.println(Math.sqrt(big * big + big * big));
    }
}
A right triangle with sides 3 and 4 and the long side 5. Beside it: Math.hypot(3, 4) = 5.0; Math.sqrt(3 * 3 + 4 * 4) = 5.0. hypot never overflows on the way: Math.hypot(1e200, 1e200) = 1.414…E200, but Math.sqrt(1e2001e200 + 1e2001e200) = Infinity.سێگۆشەیەکی ڕاستگۆشە بە لاکانی 3 و 4 و درێژترین لای 5. لە تەنیشتیەوە: Math.hypot(3, 4) = 5.0؛ Math.sqrt(3 * 3 + 4 * 4) = 5.0. hypot لە نێوەڕاستی ژماردندا سەرڕێژبوون نابێت: Math.hypot(1e200, 1e200) = 1.414…E200، بەڵام Math.sqrt(1e2001e200 + 1e2001e200) = Infinity.
The 3-4-5 triangleسێگۆشەی ⁦3-4-5⁩CêIT

Overflow-safe arithmetic: the Exact methodsژماردنی بێ سەرڕێژبوون: میتۆدەکانی Exact

int and long arithmetic wraps round silently when the answer is too big (Overflow). When a wrong number would be dangerous, such as money or a medicine dose, use Math.addExact, Math.subtractExact or Math.multiplyExact: they stop with an ArithmeticException instead:

ژماردنی int و long بە بێدەنگی دەسوڕێتەوە کاتێک وەڵامەکە زۆر گەورەیە (سەرڕێژبوون). کاتێک ژمارەیەکی هەڵە مەترسیدار دەبێت، وەک پارە یان بڕی دەرمان، Math.addExact، Math.subtractExact یان Math.multiplyExact بەکار بهێنە: لە جیاتی ئەوە بە ArithmeticException دەوەستن:

Exact.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Exact {
    public static void main(String[] args) {
        int a = 50_000;
        System.out.println(a * a);                    // too big for an int: wraps round
        System.out.println(Math.multiplyExact(a, a));  // stops with an exception
    }
}
Two bars: the largest int, 2 147 483 647, and 50 000 × 50 000 = 2 500 000 000, which goes past it. Above: a * a gives -1794967296 with a cross; Math.multiplyExact(a, a) gives an ArithmeticException with a tick. Note: a silent wrong answer, or a clear stop; the Exact methods choose the stop.دوو هێڵکاری: گەورەترین int، 2 147 483 647 و 50 000 × 50 000 = 2 500 000 000 کە لێی تێدەپەڕێت. سەرەوە: a * a دەدات -1794967296 بە نیشانەی هەڵە؛ Math.multiplyExact(a, a) دەدات ArithmeticException بە نیشانەی ڕاست. تێبینی: وەڵامێکی هەڵەی بێدەنگ، یان وەستانێکی ڕوون؛ میتۆدەکانی Exact وەستان هەڵدەبژێرن.
A wrong answer or a clear stopوەڵامی هەڵە یان وەستانی ڕوونCêIT

Without the class name: import staticبەبێ ناوی کلاسەکە: import static

There is a second way to call the methods. import static java.lang.Math.*; at the top of the file brings every static member of Math into the program, so you can write max(10, -20) without Math.:

ڕێگەیەکی دووەمیش بۆ بانگکردنی هەیە. import static java.lang.Math.*; لە سەرەوەی هەموو Math دەهێنێتە ناو ، بۆیە دەتوانیت max(10, -20) بنووسیت بەبێ Math.:

Example.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import static java.lang.Math.*;

public class Example {
    public static void main(String[] args) {
        System.out.println(max(10, -20));
        System.out.println(sqrt(16));
        System.out.println(PI);
    }
}
Two cards. With the class name (usual): Math.max(10, -20) gives 10. With import static java.lang.Math.*;: max(10, -20) gives 10. Note: the class name tells the reader where max comes from.دوو کارت. بە ناوی کلاسەکە (ئاسایی): Math.max(10, -20) دەدات 10. بە import static java.lang.Math.*;: max(10, -20) دەدات 10. تێبینی: ناوی کلاسەکە بە خوێنەر دەڵێت max لە کوێوە هاتووە.
Two ways to call maxدوو ڕێگە بۆ بانگکردنی maxCêIT

Use it sparingly: with Math. the reader sees at once where a method comes from (import static shows more uses). Without the import, sqrt(16) alone gives cannot find symbol (symbol: method sqrt(int)). Class names start with a capital letter, Example, not example (naming conventions). In IDE screenshots you may see max(a: 10, -20): the grey a: is only the editor's hint, never type it (Copy-paste traps).

کەم بەکاری بهێنە: بە Math. خوێنەر یەکسەر دەبینێت لە کوێوە هاتووە (import static نموونەی زیاتری تێدایە). بەبێ import، sqrt(16) بە تەنیا دەدات cannot find symbol (symbol: method sqrt(int)). ناوی بە پیتی گەورە دەست پێ دەکات، Example، نەک example (ڕێککەوتنەکانی ناونان). لە IDEـدا لەوانەیە max(a: 10, -20) ببینیت: a:ـە خۆڵەمێشییەکە تەنیا ئاماژەی دەستکاریکەرەکەیە، هەرگیز مەینووسە (تەڵەکانی کۆپی و لکاندن).

A program: power and roundingبەرنامەیەک: توان و نزیککردنەوە

This program reads a base and an exponent from the keyboard, computes the power and rounds it. Reading input needs Scanner, which is in the package java.util and must be imported (Two lines get a Scanner ready). Without the import line, javac reports cannot find symbol (symbol: class Scanner) twice; Math needs no import.

ئەم بنچینە و لە کیبۆردەوە دەخوێنێتەوە، دەژمێرێت و نزیکی دەکاتەوە. خوێندنەوەی پێویستی بە Scanner هەیە، کە لە java.utilـدایە و دەبێت import بکرێت (دوو دێڕ Scanner ئامادە دەکەن). بەبێ دێڕی import، javac دوو جار دەڵێت cannot find symbol (symbol: class Scanner)؛ Math پێویستی بە import نییە.

PowerAndRound.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
import java.util.Scanner;

public class PowerAndRound {

    public static void main(String[] args) {
        double a, b;
        Scanner input = new Scanner(System.in);

        System.out.print(" Enter the base number: ");
        a = input.nextDouble();

        System.out.print(" Enter the exponent number: ");
        b = input.nextDouble();

        double c = Math.pow(a, b);
        System.out.println(a + "\t power " + b + "\t =" + c);

        long roundNo = Math.round(c);
        System.out.println("the round No    " + c + " = " + roundNo);
    }
}

roundNo is a long, because Math.round returns a long: it prints 36. Stored in a double (double roundNo = Math.round(c);) the same value prints as 36.0. Other runs: 2 and 10 give 1024.0 and 1024; 2.5 and 2 give 6.25 and 6.

roundNo جۆری longـە، چونکە Math.round long دەگەڕێنێتەوە: ⁦36⁩ چاپ دەکات. ئەگەر لە doubleـدا هەڵبگیرێت (double roundNo = Math.round(c);)، هەمان وەک ⁦36.0⁩ چاپ دەکرێت. جێبەجێکردنی تر: 2 و ⁦10⁩ دەدەن ⁦1024.0⁩ و ⁦1024⁩؛ ⁦2.5⁩ و 2 دەدەن ⁦6.25⁩ و 6.

Common mistakesهەڵە باوەکان

You wroteنووسیتWhat happensچی ڕوو دەداتFixچارەسەر
2 ^ 108: XOR, not a power⁦8: XOR⁩، نەک Math.pow(2, 10)Math.pow(2, 10)
sqrt(16)cannot find symbol ... method sqrt(int)Math.sqrt(16), or a static importMath.sqrt(16)، یان importـی ستاتیک
math.sqrt(16)cannot find symbol ... variable mathMath with a capital MMath بە Mـی گەورە
Math m = new Math();Math() has private access in MathCall the methods on the class: Math.max(…). لەسەر بانگ بکە: Math.max(…).
int r = Math.round(2.7);possible lossy conversion from long to intlong r = … or (int) Math.round(2.7)long r = … یان (int) Math.round(2.7)
(int) Math.random() * 6 + 1always 1هەمیشە 1(int) (Math.random() * 6) + 1(int) (Math.random() * 6) + 1
Math.sqrt(-1)NaNNaNCheck the sign first.سەرەتا نیشانەکە بپشکنە.
Math.max(a: 10, -20)')' expectedDelete the editor hint a:.ئاماژەی دەستکاریکەر a: بسڕەوە.

Practiceڕاهێنان

ExerciseڕاهێنانA ladderپەیژەیەک

A ladder reaches 8 m up a wall, and its foot is 6 m from the wall. How long is the ladder? Use Math.hypot.

پەیژەیەک 8 مەتر بە دیوارێکدا بەرز دەبێتەوە و بنەکەی 6 مەتر لە دیوارەکەوە دوورە. پەیژەکە چەند درێژە؟ Math.hypot بەکار بهێنە.

Show answerوەڵامەکە پیشان بدە
Ladder.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Ladder {
    public static void main(String[] args) {
        double wall = 8;            // metres up the wall
        double ground = 6;          // metres from the wall
        System.out.println(Math.hypot(ground, wall));
    }
}
ExerciseڕاهێنانCircle areaڕووبەری بازنە

Print the area of a circle with radius 2.5, first in full, then rounded to two decimal places.

ڕووبەری بازنەیەک بە نیوەتیرەی ⁦2.5⁩ چاپ بکە، سەرەتا بە تەواوی، پاشان بە بۆ دوو .

Show answerوەڵامەکە پیشان بدە
CircleArea.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class CircleArea {
    public static void main(String[] args) {
        double radius = 2.5;
        double area = Math.PI * Math.pow(radius, 2);
        System.out.println(area);
        System.out.println(Math.round(area * 100) / 100.0);
    }
}
ExerciseڕاهێنانTwo diceدوو زار

Roll two dice and print both numbers and their sum.

دوو زار هەڵبدە و هەردوو ژمارەکە و کۆکەیان چاپ بکە.

Show answerوەڵامەکە پیشان بدە
TwoDice.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class TwoDice {
    public static void main(String[] args) {
        int die1 = (int) (Math.random() * 6) + 1;
        int die2 = (int) (Math.random() * 6) + 1;
        System.out.println(die1 + " + " + die2 + " = " + (die1 + die2));
    }
}

Each die needs its own call to Math.random().

هەر زارێک پێویستی بە بانگکردنێکی جیای Math.random() هەیە.

ExerciseڕاهێنانPredict the outputپێشبینیی دەرخستە بکە

What does each call give for -1.5? Math.round · Math.floor · Math.ceil · Math.rint · Math.abs · Math.max(-1.5, -2)

هەر بانگکردنێک بۆ -1.5 چی دەدات؟ Math.round · Math.floor · Math.ceil · Math.rint · Math.abs · Math.max(-1.5, -2)

Show answerوەڵامەکە پیشان بدە
PredictMath.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class PredictMath {
    public static void main(String[] args) {
        System.out.println(Math.round(-1.5));
        System.out.println(Math.floor(-1.5));
        System.out.println(Math.ceil(-1.5));
        System.out.println(Math.rint(-1.5));
        System.out.println(Math.abs(-1.5));
        System.out.println(Math.max(-1.5, -2));
    }
}

round sends the half up (toward positive infinity) to -1; rint sends it to the even -2.0; floor goes down to -2.0 and ceil up to -1.0.

round نیوەکە بەرەو سەرەوە دەبات (بەرەو ئەرێنی) بۆ -1؛ rint دەینێرێت بۆ جووتەکە -2.0؛ floor بەرەو خوار دەچێت بۆ -2.0 و ceil بەرەو سەرەوە بۆ -1.0.

ExerciseڕاهێنانDistance between two pointsدووریی نێوان دوو خاڵ

How far is the point (1, 2) from the point (4, 6)?

خاڵی (⁦1⁩، ⁦2⁩) چەند دوورە لە خاڵی (⁦4⁩، ⁦6⁩)؟

Show answerوەڵامەکە پیشان بدە
Distance.javaJAVAType in a terminalلە تێرمیناڵدا بینووسە
public class Distance {
    public static void main(String[] args) {
        double x1 = 1, y1 = 2;
        double x2 = 4, y2 = 6;
        System.out.println(Math.hypot(x2 - x1, y2 - y1));
    }
}

The sides of the triangle are 4 - 1 = 3 and 6 - 2 = 4.

لاکانی سێگۆشەکە 4 - 1 = 3 و 6 - 2 = 4ن.

Summaryکورتە

  • Math is a class of static methods in java.lang: call them as Math.name(arguments), with no import and no new.
  • max, min, abs, sqrt, cbrt, pow (Java has no power operator), hypot.
  • round (a half goes up; returns long), floor, ceil and rint (return double).
  • Math.random() gives 0.0 up to 1.0; (int) (Math.random() * 6) + 1 is a die. Random with a seed repeats.
  • Math.PI, Math.E; addExact and multiplyExact stop instead of wrapping round.
  • Math لە لە java.langـدا: وەک Math.name(arguments) بانگیان بکە، بەبێ import و بەبێ new.
  • max، min، abs، sqrt، cbrt، pow (Java نییە)، hypot.
  • round (نیوە بەرەو سەرەوە؛ long دەگەڕێنێتەوە)، floor، ceil و rint (double دەگەڕێننەوە).
  • Math.random() لە ⁦0.0⁩ تا کەمتر لە ⁦1.0⁩ دەدات؛ (int) (Math.random() * 6) + 1 زارێکە. Random بە دووپاتە دەبێتەوە.
  • Math.PI، Math.E؛ addExact و multiplyExact لە جیاتی سووڕانەوە دەوەستن.
Review questionsپرسیارەکانی پێداچوونەوە
Why can you write Math.sqrt(9) without creating a Math object?بۆچی دەتوانیت بەبێ دروستکردنی ئۆبجێکتێکی Math بنووسیت Math.sqrt(9)؟

Its methods are static members: they belong to the class itself.

Math ستاتیکن: هی خودی .

What is the difference between Math.round(4.5) and Math.rint(4.5)?جیاوازیی نێوان Math.round(4.5) و Math.rint(4.5) چییە؟

round sends the half up and gives the long 5; rint sends it to the even neighbour and gives 4.0.

round نیوەکە بەرەو سەرەوە دەبات و longـی 5 دەدات؛ rint دەینێرێت بۆ دراوسێ جووتەکە و ⁦4.0⁩ دەدات.

How do you get a whole number from 1 to 6 with Math.random()?چۆن بە Math.random() ژمارەیەکی تەواو لە 1 تا 6 وەردەگریت؟

(int) (Math.random() * 6) + 1.

(int) (Math.random() * 6) + 1.

Lesson complete!وانەکە تەواو بوو!

Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.

Key termsزاراوە سەرەکییەکان

Next lessonوانەی داهاتوو

Keyboard Input with Scanner and Formatted Outputنێوخستە لە کیبۆردەوە بە Scanner و دەرخستەی ڕێکخراو

References and further readingسەرچاوەکان و خوێندنەوەی زیاتر

This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.

Appearanceڕووکار

Modeدۆخ
Styleشێواز
Coloursڕەنگەکان

Saved on this device only.تەنیا لەسەر ئەم ئامێرە پاشەکەوت دەکرێت.