Optimized integer logarithm base2 for BigIntWhat is JavaScript's highest integer value that a number can go to without losing precision?Plot logarithmic axes with matplotlib in pythonLogarithmic sliderHow to sort an array of integers correctlyConvert a string to an integer in JavaScript?How do I check that a number is float or integer?Integer division with remainder in JavaScript?How can I get Google's Closure Compiler to eliminate attributesbigInt to base2How to obtain the amount of bits of a BigInt?

BritRail England Passes compared to return ticket for travel in England

Why didn't Doctor Strange restore Tony Stark after he used the Stones?

How long were the Apollo astronauts allowed to breathe 100% oxygen at 1 atmosphere continuously?

literal `0` beeing a valid candidate for int and const string& overloads causes ambiguous call

What is a Romeo Word™?

In this iconic lunar orbit rendezvous photo of John Houbolt, why do arrows #5 and #6 point the "wrong" way?

Pauli exclusion principle - black holes

What could make large expeditions ineffective for exploring territory full of dangers and valuable resources?

Is it legal for a supermarket to refuse to sell an adult beer if an adult with them doesn’t have their ID?

Why can't I hear fret buzz through the amp?

Proof that every field is perfect???

How important are the Author's mood and feelings for writing a story?

Is it possible to have a career in SciComp without contributing to arms research?

When designing an adventure, how can I ensure a continuous player experience in a setting that's likely to favor TPKs?

How can I automate this tensor computation?

Why are there few or no black super GMs?

Which GPUs to get for Mathematical Optimization (if any)?

Why did my "seldom" get corrected?

Do Australia and New Zealand have a travel ban on Somalis (like Wikipedia says)?

Should I have one hand on the throttle during engine ignition?

Could a US citizen born through "birth tourism" become President?

Changing iteration variable in Do loop

How to tell if JDK is available from within running JVM?

Should I have shared a document with a former employee?



Optimized integer logarithm base2 for BigInt


What is JavaScript's highest integer value that a number can go to without losing precision?Plot logarithmic axes with matplotlib in pythonLogarithmic sliderHow to sort an array of integers correctlyConvert a string to an integer in JavaScript?How do I check that a number is float or integer?Integer division with remainder in JavaScript?How can I get Google's Closure Compiler to eliminate attributesbigInt to base2How to obtain the amount of bits of a BigInt?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








3















This is the naive algorithm that calculates integer log2(n),



 function ilog2(n) // n is a positive non-zero BigInt
const C1 = BigInt(1)
const C2 = BigInt(2)
for(var count=0; n>C1; count++) n = n/C2
return count
// example ilog2(16n)==4


I am testing optimizations (see example below) but they are not "for log2", as commented here.



There are something better using WebAssembly?



PS: if it is not possible a generic solution, to solve my problem I can use functions like ilog2_64bits(n), with WebAssembly truncating or ignoring some bits of input BigInt.




non-WebAssembly



Example of not so optimized in pure Javascript (ideal is WebAssembly!)... Trying adaptation of integerLogarithm() of BigInteger.js:



 function ilog2_pe(value, base=2n) 
// example: ilog2_pe(255n) returns p: 128n, e: 7n
if (base <= value)
let i = ilog2_pe(value, base**2n);
let t = i.p*base
return (t <= value)
? p: t, e: i.e*2n + 1n
: p: i.p, e: i.e*2n

return p: 1n, e: 0n ;


function ilog2_str(n) // 2*faster!
return n.toString(2).length - 1



PS: it is running in modern browsers and last versions of NodeJS.




About performance... ilog2_pe(x64bits) is 4 times faster tham the naive ilog2(), ilog2_pe(x1024bits) is ~9 times faster... Was expected... But:



Any non-WebAssembly solution has so ugly performance, even for 512, 1024, 2048 bits... counting string digits with ilog_str() is 2 times faster!
For less tham 64 bits is 3 or more times faster.










share|improve this question






























    3















    This is the naive algorithm that calculates integer log2(n),



     function ilog2(n) // n is a positive non-zero BigInt
    const C1 = BigInt(1)
    const C2 = BigInt(2)
    for(var count=0; n>C1; count++) n = n/C2
    return count
    // example ilog2(16n)==4


    I am testing optimizations (see example below) but they are not "for log2", as commented here.



    There are something better using WebAssembly?



    PS: if it is not possible a generic solution, to solve my problem I can use functions like ilog2_64bits(n), with WebAssembly truncating or ignoring some bits of input BigInt.




    non-WebAssembly



    Example of not so optimized in pure Javascript (ideal is WebAssembly!)... Trying adaptation of integerLogarithm() of BigInteger.js:



     function ilog2_pe(value, base=2n) 
    // example: ilog2_pe(255n) returns p: 128n, e: 7n
    if (base <= value)
    let i = ilog2_pe(value, base**2n);
    let t = i.p*base
    return (t <= value)
    ? p: t, e: i.e*2n + 1n
    : p: i.p, e: i.e*2n

    return p: 1n, e: 0n ;


    function ilog2_str(n) // 2*faster!
    return n.toString(2).length - 1



    PS: it is running in modern browsers and last versions of NodeJS.




    About performance... ilog2_pe(x64bits) is 4 times faster tham the naive ilog2(), ilog2_pe(x1024bits) is ~9 times faster... Was expected... But:



    Any non-WebAssembly solution has so ugly performance, even for 512, 1024, 2048 bits... counting string digits with ilog_str() is 2 times faster!
    For less tham 64 bits is 3 or more times faster.










    share|improve this question


























      3












      3








      3


      1






      This is the naive algorithm that calculates integer log2(n),



       function ilog2(n) // n is a positive non-zero BigInt
      const C1 = BigInt(1)
      const C2 = BigInt(2)
      for(var count=0; n>C1; count++) n = n/C2
      return count
      // example ilog2(16n)==4


      I am testing optimizations (see example below) but they are not "for log2", as commented here.



      There are something better using WebAssembly?



      PS: if it is not possible a generic solution, to solve my problem I can use functions like ilog2_64bits(n), with WebAssembly truncating or ignoring some bits of input BigInt.




      non-WebAssembly



      Example of not so optimized in pure Javascript (ideal is WebAssembly!)... Trying adaptation of integerLogarithm() of BigInteger.js:



       function ilog2_pe(value, base=2n) 
      // example: ilog2_pe(255n) returns p: 128n, e: 7n
      if (base <= value)
      let i = ilog2_pe(value, base**2n);
      let t = i.p*base
      return (t <= value)
      ? p: t, e: i.e*2n + 1n
      : p: i.p, e: i.e*2n

      return p: 1n, e: 0n ;


      function ilog2_str(n) // 2*faster!
      return n.toString(2).length - 1



      PS: it is running in modern browsers and last versions of NodeJS.




      About performance... ilog2_pe(x64bits) is 4 times faster tham the naive ilog2(), ilog2_pe(x1024bits) is ~9 times faster... Was expected... But:



      Any non-WebAssembly solution has so ugly performance, even for 512, 1024, 2048 bits... counting string digits with ilog_str() is 2 times faster!
      For less tham 64 bits is 3 or more times faster.










      share|improve this question
















      This is the naive algorithm that calculates integer log2(n),



       function ilog2(n) // n is a positive non-zero BigInt
      const C1 = BigInt(1)
      const C2 = BigInt(2)
      for(var count=0; n>C1; count++) n = n/C2
      return count
      // example ilog2(16n)==4


      I am testing optimizations (see example below) but they are not "for log2", as commented here.



      There are something better using WebAssembly?



      PS: if it is not possible a generic solution, to solve my problem I can use functions like ilog2_64bits(n), with WebAssembly truncating or ignoring some bits of input BigInt.




      non-WebAssembly



      Example of not so optimized in pure Javascript (ideal is WebAssembly!)... Trying adaptation of integerLogarithm() of BigInteger.js:



       function ilog2_pe(value, base=2n) 
      // example: ilog2_pe(255n) returns p: 128n, e: 7n
      if (base <= value)
      let i = ilog2_pe(value, base**2n);
      let t = i.p*base
      return (t <= value)
      ? p: t, e: i.e*2n + 1n
      : p: i.p, e: i.e*2n

      return p: 1n, e: 0n ;


      function ilog2_str(n) // 2*faster!
      return n.toString(2).length - 1



      PS: it is running in modern browsers and last versions of NodeJS.




      About performance... ilog2_pe(x64bits) is 4 times faster tham the naive ilog2(), ilog2_pe(x1024bits) is ~9 times faster... Was expected... But:



      Any non-WebAssembly solution has so ugly performance, even for 512, 1024, 2048 bits... counting string digits with ilog_str() is 2 times faster!
      For less tham 64 bits is 3 or more times faster.







      javascript logarithm






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 26 at 23:01







      Peter Krauss

















      asked Mar 26 at 10:43









      Peter KraussPeter Krauss

      5,88611 gold badges88 silver badges191 bronze badges




      5,88611 gold badges88 silver badges191 bronze badges






















          0






          active

          oldest

          votes










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55355184%2foptimized-integer-logarithm-base2-for-bigint%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes




          Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.







          Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid …


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55355184%2foptimized-integer-logarithm-base2-for-bigint%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

          Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?