我想在组织模式文件中嵌入简单的数学表达式,例如:
sqrt(p * (1-p) * N)
其中p = 0.8,N = 10,000,根据一个简单的桌面计算器的答案是40.我没有运气得到org-babel给我这个答案......这是一个组织文件:
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...
我只是想方便地将一些数学嵌入到组织文件中。
(org-mode 7.8.03来自最近的git checkout,emacs 24.0.93.1来自最近的git chekout)
答案 0 :(得分:4)
不要因为拼写错误而自杀:)
(sqrt (* p (- 1 p)))
0.39999999999999997
添加缺少的N ..
(let ((p 0.8) (N 10000))
(sqrt (* p (- 1 p) N)))
40.0
对于bc,请尝试
scale=10
答案 1 :(得分:2)
你说:
sqrt(p * (1-p) * N)
where p=0.8, N=10,000 and the answer according to a simple desk calculator is 40.
这是正确的,但在许多代码中使用
:var N=100000
相反,即偏离10倍。
>>> from math import sqrt
>>> p = 0.8
>>> sqrt(p*(1-p)*10000)
40.0
>>> sqrt(p*(1-p)*100000)
126.49110640673517