Tag Archives: Math

365.2425 Days in a Year?

I was looking through some of the posts on Google+ and noticed that one of Douglas Crockford’s posts alluded to the fact that there are 365.2425 days on average in a year. At first I thought that the number should’ve actually been 365.25 due to us seeing a leap year every 4 years, but then I remembered that leap years don’t always happen every 4 years.

The rule is that a leap year will be a year evenly divisible by 4 and if it is evenly divisible 100 it must also be evenly divisible by 400. Therefore 1896 was a leap year, but the next leap year wasn’t observed until 1904.

Keeping all of this in mind, let’s see if we come to the same conclusion that there are 365.2425 days in a year on average. First, let’s determine how many days are in the typical 4 year period:
365 days × 4 + 1 leap day = 1,461 days

Now let’s determine how many days there actually are in a 400 year time span. Since we already have a rough calculation for 4 years, we can multiply that by 100 and then account for the 3 times the 3 leap days that wouldn’t occur because even though the year would be divisible by 4 and 100 it wouldn’t be divisible by 400:
1,461 days × 100 - 3 leap days = 146,097 days

Now let’s simply divide the number of days in a 400 year time span by 400 to get the average amount of days in a year:
146,097 ÷ 400 = 365.2425

So now you know why it is said that on average a year is 365.2425 days long. :cool:

JavaScript Snippet – Using Degrees with Cosine, Sine & Tangent

Now Available in YourJS

Yesterday I was working with Math.cos, Math.sin and Math.tan and was thinking it would be nice to have the equivalent functions which accept the values in degrees instead of radians. For that reason I wrote the following definitions for Math.cosd, Math.sind and Math.tand:

After executing the above 5 lines you will be able to get the cosine at 45° by doing Math.cosd(45) or the sine at 75° by doing Math.sind(75) or the tangent at 135° by doing Math.tand(135). WARNING: this does extend a built-in object. If you would like these functions in a separate Degrees object so as to avoid mutating a built-in object you could use this:

(function (R) {
  Degrees = {
    cosd: function(d) { return Math.cos(d * R); },
    sind: function(d) { return Math.sin(d * R); },
    tand: function(d) { return Math.tan(d * R); }
  };
})(Math.PI / 180);

Have fun! :cool:

POW Answer – Circle, Square, Circle

Last week’s problem involved using your geometry/trigonometry skills to find areas of shapes. We start off with a large (black) circle which has a (black) square inscribed in it which in turn has a (red) circle inscribed in it:
Circle Inscribed In A Square Inscribed In Another Circle

  1. Let’s start off with the equation for the area of a circle: A = π × r2 (where r is the radius)
  2. Now let’s think about the equation for area of a square: A = s2 (where s is the length of one of the sides)
  3. Next we can say that the radius of the inner circle is r1.
  4. After that let’s find the area of the red inner circle relative to r1: A1 = π × r12
  5. Now let’s find the length of the diagonal of the square (d) in which the red circle is inscribed relative to r1. This will also be the diameter of the outer circle
    1. s = r1 + r1 = 2 × r1
    2. The above is true because the red circle is inscribed in the square.
    3. d2 = s2 + s2
    4. d2 = 2 × s2
    5. d = (2 × s2)1/2
    6. d = s × 21/2
    7. d = 2 × r1 × 21/2
  6. Next we should find the area of the black circle (A2), in which the black square is inscribed, relative to r1.
    1. We will use r2 to represent the radius of the outer circle:
      1. r2 = d / 2
      2. r2 = (2 × r1 × 21/2) / 2
      3. r2 = r1 × 21/2
    2. A2 = π × r22
    3. A2 = π × (r1 × 21/2)2
    4. A2 = π × r12 × 2
  7. Lastly we should find the area of the black outer circle while excluding the area covered by the red inner circle:
    1. Let’s make the area of the black doughnut shape be represented by A3.
    2. A3 = A2 - A1
    3. A3 = (π × r12 × 2) - (π × r12)
    4. A3 = (π × r12) + (π × r12) - (π × r12)
    5. A3 = π × r12

So after doing all of the math by using a little geometry and a little algebra we end up with the A1 (red area) being equal to A3 (black area).
Filled Circles

Even though the image makes it look like there is more red than black, there really isn’t. Interesting stuff, huh? :cool:

POW – Circle, Square, Circle

Recently a friend asked why I haven’t put up any new POWs (Problems of the Week). Part of the reason is because I got lazy but the other part is because the show Numb3rs is what inspired me before and I haven’t been watching any reruns lately :razz:. Yesterday I started watching a new show called Scorpion which has a little math in it and the second episode got me thinking about inscribed shapes. Take the following three shapes for example:
Circle Inscribed In A Square Inscribed In Another Circle

Above is a picture of a circle inscribed in a square which itself is inscribed in another circle. Now if I make the inner circle red and the remaining area black the image ends up looking as follows:
Filled Circles

Using the information given, is the red area bigger or the black area? If you remember a few things from trigonometry/geometry I’m sure this math problem will be a breeze :cool:. As usual the answer to this problem of the week became available a week after the POW was published and can be found here.

JavaScript – Parsing A Number

If you should ever need to parse a number into an array of bits or a different base you can use the following function:

var splitNumber = (function(MAX) {
  for (; MAX + 1 - MAX == 1; MAX *= 2){}
  return function (num, radix) {
    // Validate num
    num = parseInt(num, 10);
    if (!isFinite(num) || 0 > num || num > MAX) {
      throw new Error('splitNumber() num argument must be a non-negative finite number less than ' + MAX);
    }
 
    // Validate radix
    radix = parseInt(radix || 10, 10);
    if (!(1 < radix && radix <= MAX)) {  // Also prevents NaN
      throw new Error('splitNumber() radix argument must be greater than 2 and less than ' + MAX);
    }
 
    return num.toString(radix).split('');
  };
})(1 << 30);

Here is an example of the tests and outputs:

I want to thank ildar for contributing the refinement of this function. 8-)

JavaScript – Fraction Part of a Number

One thing that is common knowledge about JavaScript and other languages is that floating point numbers are not always stored the way you think. Also doing math with these numbers is even more iffy. One thing I recently wanted to do was effectively the opposite of parseInt(). In other words, I just wanted the fractional part of the passed number to be returned. Thusly the following function was born:

/**
 * @license Copyright 2014 - Chris West - MIT Licensed
 */
(function(RGX) {
    frac = function(num) {
        return +(+num).toExponential().replace(RGX, function(m, neg, num, dot, offset) {
            var zeroes = Array(Math.abs(offset) + 2).join('0');
            num = (zeroes + num + (dot ? '' : '.') + zeroes).split('.');
            return +(neg + '.' + num.join('').slice(+offset + num[0].length));
        });
    };
})(/(-?)(\d+(\.?)\d*)e(.+)/);

I really got the idea from the first programming language I ever used: that of the Casio graphing calculators. The following are example calls and results for the function:

var a = frac(1.234);     // 0.234
var b = frac(56789e-3);  // 0.789
var c = frac(12345678);  // 0
var d = frac(-34.5697);  // -0.5697
var e = frac('-.9');     // -0.9
var f = frac(null);      // 0
var g = frac(undefined); // NaN
var h = frac('sdfa');    // NaN

Personally I thought it was strange that this function isn’t natively provided in most languages but there are some alternatives. One that works in some languages but not in JavaScript (nor in Python interestingly enough) is the following:

a = 34.5697;
fracPart = a % 1;
alert(fracPart);  // 0.5696999999999974

Another alternative method that seems like it should work but doesn’t in JavaScript is as follows:

a = 34.5697;
fracPart = a - parseInt(a);
alert(fracPart);  // 0.5696999999999974

For this reason, if you have a need to pull the decimal portion of a number out, feel free to use the frac function defined at the beginning of this post. 8-)

EcmaScript 6 – Math.sign()

One function I didn’t think would be doable in most browsers was the Math.sign. My main worry was that on the MDN page it specifies a difference between negative zero and positive zero. After doing some research I found this page which helped me realize there is a way to determine if you are dealing with normal zero or negative zero. With that in mind, my proposed definition for Math.sign is as follows:

Math.sign = Math.sign || function(n) {
  return (n = +n) ? n < 0 ? -1 : 1 : n;
};

As far as I can tell, this JavaScript function definition is a good equivalent to make the function available on browsers that dont yet natively provide this feature. Have fun! 8-)

EcmaScript 6 – Math.hypot()

Many know that JavaScript features vary from browser to browser. In the case of Firefox, there are many new features that have been proposed in EcmaScript 6. One of them is Math.hypot. This function adds up the squares of each argument passed and returns the square-root of that sum. In other words it could be used to find the length of the hypotenuse. Unfortunately, if you want to use this function it is not yet available in most other browsers. That is where the following snippet comes into play:

Math.hypot = Math.hypot || function() {
  var val, ret = 0, args = arguments, i = args.length;
  while (i--) {
    ret += (val = +args[i]) * val;
  }
  return Math.sqrt(ret);
};

Since there are a number of these newly proposed functions, I plan on writing a post to define a safe fallback for each one. Happy coding! 8-)

JavaScript – Pseudo Array Comprehensions

In my job I have recently switched over to primarily coding in Python and I am loving the change. One thing that I find interesting is list comprehensions. Still, since my first love is JavaScript, I wanted to be able to do something similar in JavaScript and had remembered coming across its likeness in the language (version 1.7). Unfortunately, it doesn’t seem like this is going to be globally supported very soon so below is an alternative:

/**
 * @license Array Builder - By Chris West - MIT License
 * Builds an array either from another array or an object using the values.
 * @param {!Array|!Object} obj  Array or object to be traversed and whose values
 *     will be transformed and possibly added to the returned array.
 * @param {string} varName  The name of the value as it can appear in the
 *     expression and the optFilter.
 * @param {string} expression  The JavaScript expression that will be evaluated
 *     and possibly placed in the array to be returned by this function.
 * @param {string=} optFilter  Optional filter expression that will be evaluated
 *     will be evaluated for each value and only if a truish value results will
 *     the expression be evaluated and the resulting value added to the built
 *     array.
 * @return {!Array}  The array built from the passed array or object.
 */
var buildArray = (function(hasOwnProperty, toString) {
  return function(obj, varName, expression, optFilter) {
    expression = new Function(varName, 'return ' + expression);
    if (optFilter) {
      optFilter = new Function(varName, 'return ' + optFilter);
    }
    
    var ret = [];
    
    function process(key, obj) {
      var value = obj[key];
      if (!optFilter || optFilter.call(obj, value)) {
        ret.push(expression.call(obj, value));
      }
    }
    
    if (toString.call(obj) == '[object Array]') {
      for (var i = 0, len = obj.length; i < len; i++) {
        process(i, obj);
      }
    }
    else {
      for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) {
          process(key, obj);
        }
      }
    }
    
    return ret;
  };
})({}.hasOwnProperty, {}.toString);

As you can see I have already annotated the above function, but here is an example of using it:

buildArray([1,2,3,4,5], 'x', 'x*x');
// Result:  [1, 4, 9, 16, 25]

buildArray({a:'A', b:'B', c:'C'}, 'c', 'c');
// Result:  ['A', 'B', 'C']

buildArray([1,2,3,4,5], 'i', 'String.fromCharCode(64+i)', 'i%2');
// Result:  ['A', 'C', 'E']

Also, if you are wondering why I named this function buildArray it is because this idea of comprehension lists (or JavaScript comprehension arrays) is derived from set-builder notation in mathematics. If you need, feel free to use this function in your code. 8-)