Simple math results in an Emacs org-mode file with babel
質問
I'd like to embed simple math expressions in an org-mode file, such as:
sqrt(p * (1-p) * N)
where p=0.8, N=10,000 and the answer according to a simple desk calculator is 40. I'm having no luck get org-babel give me this answer... Here's an org file:
Some weird rounding errors with Python:
#+begin_src python :var N=100000 :var p=0.8
from math import sqrt
return sqrt(p * (1 - p) * N)
#+end_src
#+results:
: 126.491106407
Some other weird rounding errors, this time with Emacs lisp:
#+begin_src elisp :var N=100000 :var p=0.8
(sqrt (* p (- 1 p) N))
#+end_src
#+results:
: 126.49110640673517
Note sure which number calc is unhappy with:
#+begin_src calc :var N=100000 :var p=0.8
sqrt(p * (1 - p) * N)
#+end_src
#+results:
| 5 | Expected a number |
Yet more weird rounding errors, using bc in the shell:
#+begin_src sh :var N=100000 :var p=0.8
echo "sqrt($p * (1 - $p) * $N)" | bc
#+end_src
#+results:
: 100.0
A different set of rounding errors with bc without using variables:
#+begin_src sh
echo "sqrt(0.8 * (1 - 0.8) * 10000)" | bc
#+end_src
#+results:
: 31.6
Looks like the variables are being substituted OK:
#+begin_src sh :var N=100000 :var p=0.8
echo "sqrt($p * (1 - $p) * $N)"
#+end_src
#+results:
: sqrt(0.8 * (1 - 0.8) * 100000)
Using extra precision directly gives the correct result:
#+begin_src sh
echo "sqrt(0.80 * (1 - 0.80) * 10000)" | bc
#+end_src
#+results:
: 40.0
So, just use extra precision in the p variable, eh:
#+begin_src sh :var N=100000 :var p=0.80
echo "sqrt($p * (1 - $p) * $N)" | bc
#+end_src
#+results:
: 100.0
No! Because it get stripped out:
#+begin_src sh :var N=100000 :var p=0.80
echo "sqrt($p * (1 - $p) * $N)"
#+end_src
#+results:
: sqrt(0.8 * (1 - 0.8) * 100000)
Please God, kill me now...
I'm just looking for a convenient way to embed some math in an org file.
(org-mode 7.8.03 from a recent git checkout, emacs 24.0.93.1 from a recent git chekout)
解決
You say:
sqrt(p * (1-p) * N)
where p=0.8, N=10,000 and the answer according to a simple desk calculator is 40.
This is correct, but in many of your codes you use
:var N=100000
instead, i.e. off by a factor of 10.
>>> from math import sqrt
>>> p = 0.8
>>> sqrt(p*(1-p)*10000)
40.0
>>> sqrt(p*(1-p)*100000)
126.49110640673517
他のヒント
Don't kill yourself over a typo:)
(sqrt (* p (- 1 p)))
0.39999999999999997
Add the missing N..
(let ((p 0.8) (N 10000))
(sqrt (* p (- 1 p) N)))
40.0
For bc, try with
scale=10
所属していません StackOverflow