Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 946141
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T22:52:03+00:00 2026-05-15T22:52:03+00:00

I use the following function to calculate log base 2 for integers: public static

  • 0

I use the following function to calculate log base 2 for integers:

public static int log2(int n){
    if(n <= 0) throw new IllegalArgumentException();
    return 31 - Integer.numberOfLeadingZeros(n);
}

Does it have optimal performance?

Does someone know ready J2SE API function for that purpose?

UPD1 Surprisingly for me, float point arithmetics appears to be faster than integer arithmetics.

UPD2 Due to comments I will conduct more detailed investigation.

UPD3 My integer arithmetic function is 10 times faster than Math.log(n)/Math.log(2).

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T22:52:03+00:00Added an answer on May 15, 2026 at 10:52 pm

    If you are thinking about using floating-point to help with integer arithmetics, you have to be careful.

    I usually try to avoid FP calculations whenever possible.

    Floating-point operations are not exact. You can never know for sure what will (int)(Math.log(65536)/Math.log(2)) evaluate to. For example, Math.ceil(Math.log(1<<29) / Math.log(2)) is 30 on my PC where mathematically it should be exactly 29. I didn’t find a value for x where (int)(Math.log(x)/Math.log(2)) fails (just because there are only 32 “dangerous” values), but it does not mean that it will work the same way on any PC.

    The usual trick here is using “epsilon” when rounding. Like (int)(Math.log(x)/Math.log(2)+1e-10) should never fail. The choice of this “epsilon” is not a trivial task.

    More demonstration, using a more general task – trying to implement int log(int x, int base):

    The testing code:

    static int pow(int base, int power) {
        int result = 1;
        for (int i = 0; i < power; i++)
            result *= base;
        return result;
    }
    
    private static void test(int base, int pow) {
        int x = pow(base, pow);
        if (pow != log(x, base))
            System.out.println(String.format("error at %d^%d", base, pow));
        if(pow!=0 && (pow-1) != log(x-1, base))
            System.out.println(String.format("error at %d^%d-1", base, pow));
    }
    
    public static void main(String[] args) {
        for (int base = 2; base < 500; base++) {
            int maxPow = (int) (Math.log(Integer.MAX_VALUE) / Math.log(base));
            for (int pow = 0; pow <= maxPow; pow++) {
                test(base, pow);
            }
        }
    }
    

    If we use the most straight-forward implementation of logarithm,

    static int log(int x, int base)
    {
        return (int) (Math.log(x) / Math.log(base));
    }
    

    this prints:

    error at 3^5
    error at 3^10
    error at 3^13
    error at 3^15
    error at 3^17
    error at 9^5
    error at 10^3
    error at 10^6
    error at 10^9
    error at 11^7
    error at 12^7
    ...
    

    To completely get rid of errors I had to add epsilon which is between 1e-11 and 1e-14.
    Could you have told this before testing?
    I definitely could not.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Let me use the following example to explain my question: public string ExampleFunction(string Variable)
I have written the following function to calculate a check digit in R. verhoeffCheck
In the following code I use bootstrapping to calculate the C.I. and the p-value
I use the following function in CodeIgniter, to get my latest tweet: function tweet($id)
I currently use the following function to generate a random hexadecimal representation of a
I am not quite sure how to use the following function: xlrd.xldate_as_tuple for the
I use the following to get a list of project files that need to
Consider the following use of template template parameters... #include <iostream> template <typename X> class
I use the following statement prepared and bound in ODBC: SELECT (CASE profile WHEN
I use the following code to create countdowns in Javascript. n is the number

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.