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

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현