Java log по основанию 2

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.

Читайте также:  Configure php in linux

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.

Источник

Calculate log base 2 of an integer in Java

This post will discuss how to calculate log base 2 of an integer value in Java.

The java.lang.Math class contains static methods for calculating the logarithms to bases 10 and e . Its log() method returns the natural logarithm (base e ), and the log10() method returns the base 10 logarithms of a double value.

The java.lang.Math class does not provide any method to calculate logarithms with respect to any base b . Mathematically, this can be determined using either of these two logarithms:

Programmatically, this can be done in Java as follows:

To calculate the base 2 logarithm, we can simply use the following function:

Please be aware that miscalculation is a risk due to imprecise floating-point arithmetic, as explained in this StackOverflow post. To completely eliminate errors, add an epsilon between 1e-11 and 1e-14 , as shown below:

That’s all about calculating log base 2 of an integer in Java.

Average rating 4.85 /5. Vote count: 27

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Читайте также:  Javascript loop for time

Like us? Refer us to your friends and help us grow. Happy coding 🙂

This website uses cookies. By using this site, you agree to the use of cookies, our policies, copyright terms and other conditions. Read our Privacy Policy. Got it

Источник

Вычисление логарифмов в Java

В этом коротком руководстве мы научимся вычислять логарифмы в Java. Мы рассмотрим как десятичные, так и натуральные логарифмы, а также логарифмы с пользовательским основанием.

2. Логарифмы​

Логарифм — это математическая формула, представляющая степень, в которую мы должны возвести фиксированное число (по основанию), чтобы получить данное число.

В своей простейшей форме он отвечает на вопрос: сколько раз нужно умножить одно число, чтобы получить другое число?

Мы можем определить логарифм следующим уравнением:

3. Вычисление десятичных логарифмов​

Логарифмы по основанию 10 называются десятичными логарифмами.

Чтобы вычислить десятичный логарифм в Java, мы можем просто использовать метод Math.log10() :

 @Test   public void givenLog10_shouldReturnValidResults()    assertEquals(Math.log10(100), 2);   assertEquals(Math.log10(1000), 3);   > 

4. Вычисление натуральных логарифмов​

Логарифмы по основанию e называются натуральными логарифмами.

Для вычисления натурального логарифма в Java мы используем метод Math.log() :

 @Test   public void givenLog10_shouldReturnValidResults()    assertEquals(Math.log(Math.E), 1);   assertEquals(Math.log(10), 2.30258);   > 

5. Вычисление логарифмов с пользовательской базой​

Чтобы вычислить логарифм с пользовательской базой в Java, мы используем следующее тождество:

 @Test   public void givenCustomLog_shouldReturnValidResults()    assertEquals(customLog(2, 256), 8);   assertEquals(customLog(10, 100), 2);   >    private static double customLog(double base, double logNumber)    return Math.log(logNumber) / Math.log(base);   > 

6. Заключение​

В этом уроке мы узнали, как вычислять логарифмы в Java.

Как всегда, исходный код доступен на GitHub .

Источник

log() in Java

The log() method in Java Math class returns natural logarithm of a value.

Natural logarithm means the base is fixed as » e e e » and the method returns the value of logarithm of the argument to the base » e e e «. Natural l o g log l o g or l n ln l n means it has a base of » e e e «, where e = 2 . 7 1 8 e=2.718 e = 2 . 7 1 8 .

Mathematically logarithm of a number is given by the equation:

logarithm of a number

Java Math log() method

The log() method of Math class is used to find the natural logarithm of the given argument i.e. log of the argument to the base e where e is the exponential constant.

Syntax of Math log() in Java

This is a static method so we don’t need an instance of Math class to invoke this method, rather we can use it directly. By default, the base is fixed to «e» .

Parameters of Math log() in Java

It takes a single argument:

If the input is not of double type, the compiler tries to convert the input to double format if possible.

Return Value of Math log() in Java

Java Math log() method returns the value of log of the argument to the base e e e . However, there are some special cases:

Value of «a» Return Value
NaN NaN
Negative number NaN
Positive Zero or Negative Zero Negative Infinity
Positive Infinity Positive Infinity

Exception of Math log() in Java

No exception is thrown by log() method of Math class in Java.

Some special cases of errors:

  • If we pass a String as input to the log() function it raises an error of incompatible types as String cannot be converted to double.
  • However, if we pass a character to the log() method, it does not throw an error as the A S C I I ASCII A S C I I value of the character is converted to double.
  • Example: Maths.log(‘e’) is same as Maths.log(101) and returns a value of 4 . 6 1 4.61 4 . 6 1 but Maths.log(«e») throws an error.

Example of Math log() in Java

Math log() in Java

We’ll check the table of return values given above.

Example 1: Radioactive Material Age

We’ll take a real-life example. The age of radioactive material is given by T = − ( 1 / λ ) ∗ l n ( A / A o ) T = -(1/λ)*ln(A/Ao) T = − ( 1 / λ ) ∗ l n ( A / A o ) , where λ λ λ is a constant for a particular element and A is the present amount while Ao is the initial amount.

The above code computes the age of the sample to be nearly 2 0 20 2 0 years.

Example 2: Negative Input

If the input/argument is negative, the output is N a N NaN N a N because logarithm of negative numbers is not defined.

Example 3: Positive Infinity

If the input is positive infinity, the output is positive infinity because logarithm to any base at positive infinity gives positive infinity.

Example 4: Zero Input

If the input is zero, the output is negative infinity because logarithm to any base at 0 gives negative infinity.

Example 5: Custom log() method

Custom Log

Custom log() method of Java returns a natural logarithm i.e. the base is » e e e «. But what if I’ve to find a logarithm of 2 5 25 2 5 to the base 5 5 5 rather than e e e . For that, we’ll use the change-of-base formula given below.

To get the logarithm of an inputted value to a custom base, we’ll divide the natural logarithm of the inputted value by the natural logarithm of custom base.

Explanation:

  • We pass a number and a custom base as input to our custom l o g B logB l o g B (number,custom_base) method.
  • l o g B ( ) logB() l o g B ( ) calculates natural logarithms of the number and the custom base.
  • Using the change of base formula the method divides the natural logarithms computed in the previous step to get the solution.

Conclusion

  • The log() method of Math class in Java returns the natural logarithm of a value, i.e. the base of the logarithm is » e e e «.
  • Result is NaN if the input is NaN or negative .
  • Result is positive infinity if the input is positive infinity.
  • Result is negative infinity if the input is positive zero or negative zero.
  • It does NOT throw any exception(s). However, if the input is a String (and not character), it throws an error because a String instance cannot be converted into a double value.

Источник

Оцените статью