\documentclass[12pt,pstricks,border=5pt]{standalone}
\usepackage{pst-func,pst-calculate}
\begin{document}
\begin{pspicture}(-1,-1)(1,1)
\def\q{\pscalculate{1/sqrt(5)}}
\def\a{\pscalculate{(1+sqrt(5))/2}}
\foreach \i in {0,1,...,10}{\pscalculate{\q*((\a)^(\i)-(1-\a)^(\i))},}
\end{pspicture}
\end{document}
我想生成一个斐波那契数列列表,但没有尾随零。
如何删除尾随的零?
答案1
\psCalculate
(大写 C)可以接受一些设置。
\documentclass[12pt,border=5pt]{standalone}
\usepackage{pst-calculate,pgffor}
\def\q{\pscalculate{1/sqrt(5)}}
\def\a{\pscalculate{(1+sqrt(5))/2}}
\begin{document}
$0\foreach \i in {1,...,10}{,\psCalculate[round-mode=places,round-precision=0]{\q*((\a)^(\i)-(1-\a)^(\i))}}$
\end{document}
答案2
使用简单的 LaTeX 命令来计算斐波那契数:
\documentclass{article}
\usepackage{ifthen}
\newcounter{fiba}\newcounter{fibb}\newcounter{fibc}\newcounter{fibrun}
\newcommand\fib[1]{%
\init\whiledo{\thefibrun<#1}{\step\stepcounter{fibrun}}\thefiba}
\newcommand\init{%
\setcounter{fiba}{1}\setcounter{fibb}{1}\setcounter{fibrun}{0}}
\newcommand\step{\add \rotate}
\newcommand\add{\setcounter{fibc}{\thefiba}\addtocounter{fibc}{\thefibb}}
\newcommand\rotate{\setcounter{fiba}{\thefibb}\setcounter{fibb}{\thefibc}}
\begin{document}
\newcounter{i} \newcounter{en} \setcounter{en}{20}
the first \theen\ Fibonacci numbers:\\
\whiledo{\thei < \theen}{$\fib{\thei}$ \stepcounter{i}}
\end{document}
和跑步一样lualatex
:
\documentclass[12pt,a4paper]{article}
\usepackage{luacode}
\begin{luacode*}
function printFib(n)
for i=1,n do tex.print(Fibonacci(i).." ") end
end
function Fibonacci(n)
local function inner(m)
if m < 2 then return m end
return inner(m-1) + inner(m-2)
end
return inner(n)
end
\end{luacode*}
\begin{document}
\noindent\directlua{printFib(35)}
\end{document}
答案3
有人应该rlatex
立即创建一个编译器,但与此同时,我将解决knitr
预处理问题。以下是.Rnw
文件:
\documentclass[12pt,border=1cm]{standalone}
\begin{document}
<<Fib,echo=F>>=
Fibonacci <- function(n) {
x <- c(0,1)
while (length(x) < n) {nth <- length(x)
new <- x[nth] + x[nth-1]
x <- c(x,new)}
return(x)}
@
\Sexpr{combine_words(Fibonacci(11))}.
\end{document}
答案4
只是为了好玩。没有舍入,也没有pscalculate
。该示例直接复制自 pgfmanual 第 640 页。我确认了前十个数字这个答案(但有传言说,一位名叫斐波那契的数学家更早发现了它们 只是在开玩笑!;-)。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{math}
\begin{document}
\tikzmath{
% Adapted from http://www.cs.northwestern.edu/academics/courses/110/html/fib_rec.html
function fibonacci(\n) {
if \n == 0 then {
return 0;
} else {
return fibonacci2(\n, 0, 1);
}; };
function fibonacci2(\n, \p, \q) {
if \n == 1 then {
return \q;
} else {
return fibonacci2(\n-1, \q, \p+\q);
};
};
int \f, \i;
for \i in {0,1,...,20}{
\f = fibonacci(\i);
print {\f, };
};
}
\end{document}