Javascript serenity prayer

Dec. 26th, 2013 | 05:05 pm

I'm going to make this my New Year's resolution as well:

Javascript serenity prayer

God, grant me serenity to accept the Javascript I cannot change,
The courage to change the Javascript I can,
And wisdom to know the difference.
-- @eric_s_smith

Link | Leave a comment | Add to Memories | Share

Big Emacs reference card updated

Apr. 24th, 2013 | 12:18 pm

With the release of Emacs 24.3 last month and the big changes at EmacsWiki, I've posted an updated version of the giant Emacs reference card. It now contains new sections on Calendar mode, Ediff and Abbrev mode. There are also new example commands for keyboard macros, Dired Mode, Occur Mode, table.el and Calc.

There are now more than 2000 commands up from 1500. It should also be consistent with the latest version of Emacs.

It is released under a bunch of free licenses, including version 2 or later of the GNU GPL and version 1.2 or later of the GNU FDL, so people are free to share and modify it.

Link | Leave a comment {3} | Add to Memories | Share

M-x in Emacs 24.3 is now in Lisp

Mar. 11th, 2013 | 01:26 pm

It didn't make the NEWS file for Emacs 24.3, but Emacs now ships with an `M-x' (`execute-extended-command') that is written in Lisp. It is no longer written in C. This should make it easy for users to extend and do new things with this command (execute command name at point, display prefix arguments numerically, ...) by easily redefining it. Although, it was possible to "advise" the C implementation before given Emacs good advising system with `defadvice'.

I had talked about Coding Emacs's M-x in Lisp on this blog over 3 years ago. It was accepted in Emacs after I finally got around to posting the code to gnu-emacs-sources last year.

Thanks to Stefan Monnier, one of the lead maintainers, for doing most of the leg work of merging these bits into Emacs.

Link | Leave a comment | Add to Memories | Share

Frobbing pi in Emacs Lisp

Nov. 27th, 2012 | 05:53 pm

What follows is 500 years of technique used to calculate pi -- in Emacs -- up to 1997. No, Leibniz didn't write Emacs. However, the Lisp available in Emacs is pretty expressive although it has limited floating point support (it lacks bignum). For the traditional mathematical notation, see the article on pi at Wikipedia which this article is based on.

This is 17th century technology for calculating pi in 3 Lisp functions:

(defun pi-Gregory-Leibniz-term (i)
  (/ (* (expt -1 i) 4)
     (1+ (* 2.0 i))))

(defun pi-Gregory-Leibniz-series (n)
  (mapcar (lambda (i) (pi-Gregory-Leibniz-term i))
          (number-sequence 0 n)))

(defun pi-Gregory-Leibniz-sum (n)
  (apply '+ (pi-Gregory-Leibniz-series n)))

After summing 3 million terms (wait for it!) you get the 6th digit of pi.

(pi-Gregory-Leibniz-sum 2900000)
;=> 3.1415929984172606

The numbers after the 6th decimal digit are incorrect.

Here's an iterative version of the above defined in a single function:

(defun pi-Gregory-Leibniz-sum (n) ;; Now 20% faster!
  (let ((sum 0.0))
    (dotimes (i n)
      (setq sum (+ sum
                   (/ (* (expt -1 i) 4)
                      (1+ (* 2.0 i))))))
    sum))

Using the summed series to calculate pi, discovered at about the time calculus was invented, was a simplification of previous formula using infinite products discovered in the 16th century:

(defun pi-Viete (n)
  (let ((prod 1.0)
        (sqrt2 (sqrt 2))
        (sqrt-sum 0))
    (dotimes (i n)
      (setq prod (* prod
                    (sqrt (+ 2 sqrt-sum)))
            sqrt-sum (sqrt (+ 2 sqrt-sum))))
    (/ (expt 2 (1+ n)) prod)))

After 25 iterations, the product series finds the 15th digit.

(pi-Viete 25)
;=> 3.141592653589792

This is early 19th century technology:

(defun pi-Gauss-Legendre (n)
  (let ((a 1.0)
        (b (/ 1 (sqrt 2)))
        (z (/ 1.0 4))
        (p 1.0))
    (dotimes (i n)
      (let* ((a_n+1 (/ (+ a b) 2.0))
             (b_n+1 (sqrt (* a b)))
             (z_n+1 (- z (* p (expt (- a a_n+1) 2))))
             (p_n+1 (* 2 p)))
        (setq a a_n+1
              b b_n+1
              z z_n+1
              p p_n+1)))
    (/ (expt (+ a b) 2)
       (* 4 z))))

In 3 iterations it gets 14 digits of pi.

(pi-Gauss-Legendre 3)
;=> 3.141592653589794

This is 1914 technology (fac is the factorial function):

(defun pi-Ramanujan (n)
  (let ((sum 0.0))
    (dotimes (k n)
      (let ((4k (* 4 k)))
        (setq sum (+ sum
                     (/ (* (fac 4k) (+ 1103 (* 26390.0 k)))
                        (* (expt (fac k) 4) (expt 396.0 4k))))))
    (/ 9801 (sqrt 2) 2 sum))))

It gets 15 digits in 2 iterations.

(pi-Ramanujan 2)
;=> 3.1415926535897936

This route was found in 1987:

(defun pi-Chudnovsky (n)
  (let ((sum 0.0))
    (dotimes (k n)
      (let ((3k (* 3 k))
            (6k (* 6 k))
            (k! (fac k)))
      (setq sum (+ sum
                   (/ (* (fac 6k) (+ 13591409 (* 545140134.0 k)))
                      (* (fac 3k) (expt k! 3) (expt -640320.0 3k))))))
    (/ (* 426880 (sqrt 10005)) sum)))

It gets 14 digits in 1 iteration.

(pi-Chudnovsky 1)
;=> 3.141592653589734

This is 1995 technology:

(defun pi-Ploufe (n)
  (let ((sum 0))
    (dotimes (i n)
      (let ((8i (* 8 i)))
        (setq sum (+ sum
                     (/ (- (/ 4.0 (+ 8i 1))
                           (/ 2.0 (+ 8i 4))
                           (/ 1.0 (+ 8i 5))
                           (/ 1.0 (+ 8i 6)))
                        (expt 16.0 i))))))
    sum))

It can get 14 digits of pi in 11 iterations.

(pi-Ploufe 11)
;=> 3.141592653589793

This is 1997 technology.

(defun pi-Bellard (n)
  (let ((2^2  4.0)
        (2^5  32.0)
        (2^6  64.0)
        (2^8  256.0)
        (2^10 1024.0)
        (sum 0))
    (dotimes (i n)
      (let ((4i (* 4 i))
            (10i (* 10 i)))
        (setq sum (+ sum
                     (*
                      (/ (expt -1 i)
                         (expt 2^10 i))
                      (+ (- (/ 2^5 (1+ 4i)))
                         (- (/ 1.0 (+  4i 3)))
                            (/ 2^8 (+ 10i 1))
                         (- (/ 2^6 (+ 10i 3)))
                         (- (/ 2^2 (+ 10i 5)))
                         (- (/ 2^2 (+ 10i 7)))
                            (/ 1.0 (+ 10i 9))))))))
    (* (/ 1 2^6) sum)))

In 5 iterations it gets 14 digits of precision of pi.

(pi-Bellard 5)
;=> 3.1415926535897927

This article is a follow-up to another Lisp math article, Frobbing primes with Emacs Lisp, which -- if you got this far -- you may also enjoy.

Link | Leave a comment {2} | Add to Memories | Share

Prius saves gas money? (follow-up)

Apr. 17th, 2012 | 08:21 am

Toyota makes the Prius -- a popular hybrid car that gets around 50 miles to the gallon (21 km/L, 4.7L/100km). Presumably, these vehicles save you money at the fuel pump. However, their sticker price is seemingly high. One way to check the economic argument is to compare its total cost with a similar but non-hybrid conventional car and see when driving a hybrid starts saving you money. A convenient and fair comparison is the Corolla also made by Toyota.

Almost 5 years ago, Bill McGonigle compared a Prius with a Corolla and found that only after driving 280613 miles (451603 km) will you start saving money. I confirmed his math with some simple Lisp programming. Has this result changed?

Five years later, the price of gas is up to 4 dollars (US) from 3 dollars but the price point for a Prius is higher. You still need to drive 229354 (369109 km) miles before you start saving gas money. That's 60000 miles (96560 km) less than 5 years ago. Here's the arithmetic in the Emacs Lisp programming language.

(let ((gas-price 4.0)         ;; dollars/gallon
      (prius-price 24000.0)   ;; US dollars
      (corolla-price 16130.0) ;; US dollars
      (prius-mileage 48.0)    ;; miles/gallon
      (corolla-mileage 34.0)) ;; miles/gallon
  (/
   (* prius-mileage corolla-mileage
      (/ (- prius-price corolla-price) gas-price))
   (- prius-mileage corolla-mileage)))

Toyota has introduced a new c model of the Prius this year. A smaller-sized version, it is tuned to get better mileage in the city -- better than it does for highway driving. It's also 15% cheaper than the regular Prius. If you compared a city-driving Corolla with the Prius c you'd only have to drive 38802 miles (62446 km). That's pretty good, but is it a fair comparison? Here's that arithmetic before I answer that question.

(let ((gas-price 4.0)         ;; dollars/gallon
      (priusc-price 18950.0)  ;; US dollars
      (corolla-price 16130.0) ;; US dollars
      (priusc-mileage 53.0)   ;; miles/gallon
      (corolla-mileage 27.0)) ;; miles/gallon
  (/
   (* priusc-mileage corolla-mileage
      (/ (- priusc-price corolla-price) gas-price))
   (- priusc-mileage corolla-mileage)))

Average drivers don't earn 15000 miles (24140 km) a year in the city. Most of those miles are at a highway's pace. Further, the smaller Prius c is more comparable to the Toyota Yaris than a Corolla. Comparing the lower sticker price and highway mileage of a Yaris with the Prius c driven on the highway requires driving 264112 miles (425047 km). Here's the arithmetic.

(let ((gas-price 4.0)         ;; dollars/gallon
      (priusc-price 18950.0)  ;; US dollars
      (yaris-price 14115.0)   ;; US dollars
      (priusc-mileage 46.0)   ;; miles/gallon
      (yaris-mileage 38.0))   ;; miles/gallon
  (/
   (* priusc-mileage yaris-mileage
      (/ (- priusc-price yaris-price) gas-price))
   (- priusc-mileage yaris-mileage)))

After 5 years, the hybrid car still isn't economical unless a typical owner drives one for 15 years. According to Consumer Reports, Toyota's reputation for reliability is extending to the Prius, where a Prius is able to maintain its efficiency and the batteries have held up after 10 years. However, the average Prius owner probably doesn't hold on to the car this long.

More likely, consumers purchase hybrid vehicles because of their reduced environmental impact. It's estimated that just producing a car can be 10 to 20% of a vehicle's lifetime emissions. Presumably, the energy to make a Prius is greater than a conventional car since it has two engines (combustion and electrical) and additional battery. However, Toyota doesn't release the estimated emissions from manufacturing a Prius.

The city-optimized Prius c is a triple threat in metropolitan areas for its lower price, better efficiency and reduce impact on smog. However, these places typically have mass transit. The best way to save money is commute by walking, biking, car pooling or taking the bus or train. These options are better for the environment as well.

Link | Leave a comment {19} | Add to Memories | Share

Spring cleaning

Jan. 5th, 2012 | 12:09 pm

After 50 years as an academic economist, spending it deconstructing the neo-classical economics of Alfred Marshall and his "Cambridge School" -- of which she was a member early in her career -- and producing work deserving of a Nobel Prize, Joan Robinson would instead see the system resurrected in the US -- notably by the "Chicago School" of Milton Friedman and Fred Hayek. In 1980, she commented on the poverty of orthodox economics and sketched a solution.

After the Second World War, the baton of leadership in teaching economics, along with leadership in the capitalist world, passed to the USA. Instead of meeting the challenge of the Keynesian revolution head on, the profession in the USA split the subject into two parts, macro and micro. In the macro section it was permissible to contemplate fluctuations in employment and even to hint at remedies for a deficiency in effective demand, while micro theory returned to the analysis of equilibrium established by the free play of market forces. Keynesian ideas were allowed a certain sphere of operation while the central doctrine was safely walled off from them.[...]

The whole subject [of inequality] is so embarrassing that in fact it is scarcely mentioned. There is no treatment at all of the determination of the distribution of income in orthodox teaching, and precious little about its consequences. What to the general public appears one of the most interesting of all questions in economics is simply left out of the syllabus.

In its general influence on educated public opinion, orthodox teaching has been not merely feeble and confused but positively pernicious. It gives support to the view that expenditure by a government that is beneficial to the inhabitants of its territory is 'socialism' and must be prevented at all costs. This reconciles an otherwise more or less sane and benevolent public opinion to the arms race which seems to be dragging us all to destruction. But that is another story.

It seems to me that the whole complex of theories and models in the textbooks is in need of a thorough spring cleaning. We should throw out all self-contradictory propositions, unmeasurable quantities and indefinable concepts and reconstruct a logical basis for analysis with what, if anything, remains.

From the essay "The theory of normal prices and reconstruction of economic theory" published in Issues in contemporary macroeconomics and distribution edited by George R. Feiwel.

Tags:

Link | Leave a comment | Add to Memories | Share

Emacs custom global key bindings

Dec. 13th, 2011 | 12:20 pm

The only place reserved for users to put custom global key bindings in Emacs is `C-c LETTER'. (Obviously, all Emacs key bindings can be changed at ones own peril and people often do.) Here's some examples.

(global-set-key (kbd "C-c r") 'query-replace-regexp)
(global-set-key (kbd "C-c i") 'insert-buffer)
(global-set-key (kbd "C-c w") 'write-region)

I also used to like having short aliases for `M-x'. Here's some popular ones used for working with Emacs Lisp.

(defalias 'tdoe 'toggle-debug-on-error)
(defalias 'eval- 'eval-region) ;; M-x eval
(defalias 'load- 'load-file) ;; M-x load
(defalias 'ff 'find-function)
(defalias 'fv 'find-variable)
(defalias 'fl 'find-library)
(defalias 'll 'load-library)

I've come across the strategy of using `C-c' and short words or phrases for key bindings rather than single keys.

(global-set-key (kbd "C-c now")
                (lambda ()
                  "Insert current universal time."
                  (interactive "*")
                  (insert
                   (format-time-string "%Y-%m-%d %H:%M UTC"
                                       (current-time) 'universal))))

(global-set-key (kbd "C-c file") 
                (lambda (file &optional args)
                  "Insert name of FILE into buffer after point."
                  (interactive "*fInsert file name: \nP")
                  (cond ((eq '- args)
                         (insert (file-relative-name file)))
                        ((not (null args))
                         (insert (expand-file-name file)))
                        (t
                         (insert file)))))

(global-set-key (kbd "C-c fill") 'fill-region)
(global-set-key (kbd "C-c delete") 'delete-region)
(global-set-key (kbd "C-c svn") 'svn-status)
(global-set-key (kbd "C-c git") 'magit-status)
(global-set-key (kbd "C-c compile") 'compile)
;; Same as M-x recompile
(global-set-key (kbd "C-c recompile") 'recompile) 

(global-set-key (kbd "C-c copy SPC line") ;; Repeat with `C-x z'
                (lambda ()
                  (interactive)
                  (forward-line 1)
                  (open-line 1)
                  (copy-from-above-command))) ;; From misc.el
;; Same as M-x copy above RET
(global-set-key "\C-ccopy above" 'copy-from-above-command)

For the seeing Emacs user, display the keys you've pressed earlier by modifying this variable to something closer to the speed of the human eye. By default, Emacs only shows the keys you've entered in the echo area after every one second.

(setq echo-keystrokes 0.02)

It's nice how Emacs automatically creates prefix key maps for these long key sequences. For instance, `C-c compile' and `C-c copy line' share the `C-c c' and `C-c co' prefixes. However, there is no way to use both single key bindings and the new longer ones simultaneously should they share letters. When they conflict, the shorter will get stomped by the longer version. For example, the previous single key binding for `C-c r' will not work since it gets shadowed by `C-c recompile'.

I'm using a mix of both short and long key bindings since there are some editing commands that I need to keep on a short key binding but some less frequently used commands on single key bindings that I couldn't remember easily. Although, it is a delicate dance of picking useful short phrases that don't conflict with single key bindings and vice versa. I'm not planning to get carried away with it all. I'm a satisfied user of M-x.

Link | Leave a comment | Add to Memories | Share

World War Two Veteran Quote

Nov. 11th, 2011 | 11:50 am

I don’t think there’s ever been a good war, never been one. It’s the height of ignorance. I mean, it’s legalized murder. You’re killing somebody and then your mother teaches you to believe in God and then, at 17, they say now we’re gonna show you how to kill. It’s too schizophrenic. It doesn’t make sense. We should believe in God, believe in being a human being, and giving to the earth instead of taking from it. -- Anthony Dominick Benedetto

Tony Bennett recently received criticism for making the obvious point about a so-called war on terrorism, "But who are the terrorists? Are we the terrorists or are they the terrorists? Two wrongs don’t make a right."

Tony Bennett served in the the US Army and a tour in the final year of the second World War that began in France and ended in Germany. He saw the Battle of the Bulge, spent winter months in a foxhole, engaged in town-to-town fighting and liberated one of the German concentration camps at Dachau.

It's said that freedoms in the US were and are fought for in wars here and abroad. If you fight in a war don't you get the right to speak freely? It was a corollary that never existed. It was invented.

Studies have shown that recent veterans are facing unemployment at twice the US average. Returning veterans represent nearly 1/5 of all suicides. More recently, Dover Air Force Base has been found to be mishandling the remains of soldiers returning from US occupations and interventions.

I do not participate in the genuflection and formal observance of Veteran's Day, but will support the rights and respect of veterans every day of the year.

Link | Leave a comment | Add to Memories | Share

Update to big Emacs reference card

Aug. 10th, 2011 | 09:58 am

For the first time in over 2 years, I finally got around to updating my giant Emacs reference card. There are now more than 1500 commands up from 1000. It should also be consistent with the latest version of Emacs.

I transform the Wiki markup from a simple text markup using some "quick and dirty" Emacs Lisp. Besides being easier to work on than Wiki markup, the source format is also printable. The HTML version is almost 60 pages. Using a2ps on the text format it prints on 15 pieces of paper.

It's a lot of work, but it's a good way for me to learn more about Emacs. Hopefully, others will find it useful, too. I suggest printing only a few sections that you would like to improve on.

Since it is released under a bunch of free licenses, including version 2 or later of the GNU GPL and version 1.2 or later of the GNU FDL, people are free to share and modify it.
Tags:

Link | Leave a comment {1} | Add to Memories | Share

Learning Emacs key bindings

Jul. 13th, 2011 | 03:14 pm

Emacs key bindings are intimidating at first since they are quite distinct from those used in other applications and platforms. The following is based on discussion on the Emacs IRC channel and is posted to the Emacs Wiki.

After studying the tutorial that comes with Emacs, most people learn best by doing and not just by reading over a list of commands and trying to memorize them. Get yourself a text file to play around with. Make a backup copy if you're nervous about losing it. But don't worry -- Emacs makes it hard to lose your work, and it has a great undo command: `C-/' or `C-_'.

Keep the following advice in mind.

  1. Try to memorize the most commonly used commands in the tutorial.
  2. Use Apropos or help to find commands to accomplish a task.
  3. Run the command for a task with `M-x' and typing it in.
  4. Run the command again by using `M-x M-p' or by typing it in again.
  5. On the third time, see if the command is bound to a key binding with `C-h w'.
  6. If you forget a key binding (sometimes you forget even the basic commands introduced in the tutorial), try `C-h w M-p' to peek at it again or use `C-h b' to browse the available bindings.
  7. If you can't burn a key binding in to your brain with this approach, then you're not using it enough and it doesn't deserve a key binding.
  8. If a key binding is atrocious, only then bind the command to an unused key.

Some beginners rush too quickly and add or change key bindings. This avoids learning Emacs and risks spending more time configuring. Competency with `M-x' and help are actually core Emacs skills for life. `M-x' should become your command line in Emacs.

Link | Leave a comment | Add to Memories | Share