Converting decimal numbers to fractions

Given that computer numbers have a finite precision, a calculation like 20/3 produces a result like 6.66667, which is slightly off. This begs the question: can we reverse the division operation, to make a routine that outputs “20/3” when it’s given the approximate value?

One trick is to take a large number as the denominator. For the numerator you multiply the floating point number with that large number and round the result. But this is suboptimal because we would get for example 66667/10000; never the expected 20/3. Can we do any better?

Continue reading “Converting decimal numbers to fractions”

From UTF-16 to UTF-8… in JavaScript

JavaScript Strings are “finite ordered sequence of zero or more 16-bit unsigned integer values.” Usually these integer values are UTF-16 code units. The UTF-16 encoding uses one 16-bit unit for Unicode characters from U+0000 to U+FFFF, and two units for characters from U+10000 to U+10FFFF. Unfortunately all the usual String functions length, charAt, charCodeAt, are defined with respect to these code units, so characters such as 𝄞 (U+1D11E MUSICAL SYMBOL G CLEF) appear as a pair of surrogate characters. This little detail makes it complicated to operate on Strings.

This little JavaScript function encodes a string as an array of integers using UTF-8 encoding while taking surrogate pairs into account:

Did you know this about AUTO_INCREMENT?

The AUTO_INCREMENT feature of MySQL is the easiest way to generate an automatic sequence of incrementing values for a primary key. It’s very easy to use, too:

create table t (
    i integer auto_increment,
    other_field varchar(100),
    primary key(id)
);

There some features and “features” that you have to keep in mind when using AUTO_INCREMENT, though.

Continue reading “Did you know this about AUTO_INCREMENT?”