Math powers in java

How to use the Math.pow() method in Java

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

The Math.pow() is an built-in method in Java Math class and is used to calculate the power of a given number.

The power of a number refers to how many times to multiply the number with itself.

Method signature

The signature of the pow() method is as follows:

  • The method takes the base and exponent parameters of type double .
  • The method calculates multiplication of the base with itself exponent times and returns the result of type double .

See the following code snippet for example:

double pow(double base, double exponent)

Example

The pow() method is a part of java.lang.Math class, you need to import this class in your code to use the function.

Using the pow() method let’s calculate the following:

import java.lang.Math;
class CalculatePower
public static void main( String args[] )
//Calculating 5^4 and casting the returned double result to int
int ans1 = (int) Math.pow(5,4);
System.out.println("5^4 is "+ans1);
//Calculating 1.5^3 and storing the returned double result to ans2
double ans2 = Math.pow(1.5,3);
System.out.println("1.5^3 is "+ans2);
//Calculating 100^5 and casting the returned double result to int
double ans3 = Math.pow(50,5);
System.out.println("50^5 is "+ans3);
>
>

Learn in-demand tech skills in half the time

Источник

Как выполнить возведение в степень в Java

Java-университет

Hello world! Погуглить что-нибудь или попросить помощи на форуме — обычное дело даже для опытного программиста. Но есть в разработке насколько базовые и простые темы, что их должен знать даже зеленый новичок. И вот одна из таких тем. Сегодня поговорим о том, как выполняется возведение в степень в языке Java. Как выполнить возведение в степень в Java - 1Представим на секундочку, что вам дали задачу: найти число в определенной степени. Звучит довольно просто, но каким образом реализовать решение? Давайте рассмотрим самый распространенный способ и несколько альтернативных. А прежде чем “нырнуть” в решения, вначале вспомним, что такое возведение числа в степень: Как выполнить возведение в степень в Java - 2Возведение в степень — это действие, при котором одно число умножается на само себя несколько раз. Число, которое умножается, называется основанием, а количество раз умножения — показателем. Ну а результат этого самоумножения основания называется возведением в степень. Например, для 8 — это 2 в третьей степени, поскольку 2х2×2=8. Возведение какого-либо числа во вторую степень указывает на то, что мы делаем его множителем два раза, и как правило эта степень называется квадратной. То есть 4 в квадрате = 4х4 = 16. Итак, память мы освежили, а теперь переходим непосредственно к способам применения pow в Java — метода для возведения в степень.

    Math pow Самый простой способ решения поставленной задачи — использовать класс Math. Это то решение, которое вы будете использовать в большинстве случаев. Как выполнить возведение в степень в Java - 3Класс Math содержит методы, связанные с тригонометрией, геометрией и другими аспектами математики. В нём методы реализованы как статические, поэтому можно сразу вызывать через имя класса Math без создания объекта класса. Как у нас будет выглядеть возведение в степень:
 public static int pow(int value, int powValue)
 public static int pow(int value)
 public static void main(String[] args)
 public static void main(String[] args) < System.out.println(Solution.pow(7, 4)); >public static int pow(int value, int powValue) < int result = 1; for (int i = 1; i return result; > 

Как выполнить возведение в степень в Java - 4

Алгоритм весьма прост: мы как бы задаём точку отсчета result, и далее умножаем его на наше значение value столько раз, сколько отработает цикл с powValue (powValue количество раз)
Рекурсия Следующий способ будет немного более экзотическим, но от этого не менее крутым. Рекурсия — это средство, которое позволяет методу вызывать самого себя. В Java такой механизм присутствует, и такие методы, соответственно, называются рекурсивными. Многие, если не все алгоритмические задачки, можно решать рекурсивно. Данная тоже не будет исключением, поэтому давайте взглянем, как можно возвести число в определенную степень рекурсивным способом:

 public static int pow(int value, int powValue) < if (powValue == 1) < return value; >else < return value * pow(value, powValue - 1); >> 
  1. Условие выхода из рекурсии, или другими словами, когда у нас значение степени достигнет единицы, нас начнёт выбрасывать назад.
  2. Сам механизм умножения value на результат вызова этого же метода, но с powValue — 1.

Ну а теперь пришло время взглянуть на более ленивые способы, а именно — способы “из коробки”.

Как выполнить возведение в степень в Java - 5

BigInteger Главное назначение класса BigInteger состоит в хранении целых чисел произвольной величины, но при этом в нём есть различные арифметические методы, позволяющие вести работу с этими огромными (ну или не очень) числами. Подробнее о BigInteger можно почитать вот в этой статье. Итак, как же будет выглядеть возведение в степень с помощью BigInteger в Java?

 public static int pow(int value, int powValue)

Как выполнить возведение в степень в Java - 6

Довольно просто и без заморочек, не правда ли?

Ну вот, на сегодня все! Теперь вы знаете о самых разных способах возведения в степень. Согласитесь, это была несложная тема 🙂

Источник

Class Math

The class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.

Unlike some of the numeric methods of class StrictMath , all implementations of the equivalent functions of class Math are not defined to return the bit-for-bit same results. This relaxation permits better-performing implementations where strict reproducibility is not required.

By default many of the Math methods simply call the equivalent method in StrictMath for their implementation. Code generators are encouraged to use platform-specific native libraries or microprocessor instructions, where available, to provide higher-performance implementations of Math methods. Such higher-performance implementations still must conform to the specification for Math .

The quality of implementation specifications concern two properties, accuracy of the returned result and monotonicity of the method. Accuracy of the floating-point Math methods is measured in terms of ulps, units in the last place. For a given floating-point format, an ulp of a specific real number value is the distance between the two floating-point values bracketing that numerical value. When discussing the accuracy of a method as a whole rather than at a specific argument, the number of ulps cited is for the worst-case error at any argument. If a method always has an error less than 0.5 ulps, the method always returns the floating-point number nearest the exact result; such a method is correctly rounded. A correctly rounded method is generally the best a floating-point approximation can be; however, it is impractical for many floating-point methods to be correctly rounded. Instead, for the Math class, a larger error bound of 1 or 2 ulps is allowed for certain methods. Informally, with a 1 ulp error bound, when the exact result is a representable number, the exact result should be returned as the computed result; otherwise, either of the two floating-point values which bracket the exact result may be returned. For exact results large in magnitude, one of the endpoints of the bracket may be infinite. Besides accuracy at individual arguments, maintaining proper relations between the method at different arguments is also important. Therefore, most methods with more than 0.5 ulp errors are required to be semi-monotonic: whenever the mathematical function is non-decreasing, so is the floating-point approximation, likewise, whenever the mathematical function is non-increasing, so is the floating-point approximation. Not all approximations that have 1 ulp accuracy will automatically meet the monotonicity requirements.

The platform uses signed two’s complement integer arithmetic with int and long primitive types. The developer should choose the primitive type to ensure that arithmetic operations consistently produce correct results, which in some cases means the operations will not overflow the range of values of the computation. The best practice is to choose the primitive type and algorithm to avoid overflow. In cases where the size is int or long and overflow errors need to be detected, the methods whose names end with Exact throw an ArithmeticException when the results overflow.

The 2019 revision of the IEEE 754 floating-point standard includes a section of recommended operations and the semantics of those operations if they are included in a programming environment. The recommended operations present in this class include sin , cos , tan , asin , acos , atan , exp , expm1 , log , log10 , log1p , sinh , cosh , tanh , hypot , and pow . (The sqrt operation is a required part of IEEE 754 from a different section of the standard.) The special case behavior of the recommended operations generally follows the guidance of the IEEE 754 standard. However, the pow method defines different behavior for some arguments, as noted in its specification. The IEEE 754 standard defines its operations to be correctly rounded, which is a more stringent quality of implementation condition than required for most of the methods in question that are also included in this class.

Источник

Читайте также:  Html link full width
Оцените статью