TeX - LaTeX Asked on August 27, 2021
I want to produce a random number and with this check an if statement.
But it does not work. I tried the following:
documentclass{minimal}
usepackage[first=0, last=1]{lcg}
newcommand{random}{randarabic{rand}}
begin{document}
defvar{random}
ifnumvar=1
We have a one.
fi
ifnumvar=0
We have a zero.
fi
end{document}`
I thought that the reason might be that the variable var is not of the same type as 0 or 1.
Can anybody help?
rand
is not “expandable”. It is an instruction for setting a counter, namely rand
to some value.
Thus ifnum
doesn't find just a number, but a set of instructions to produce one.
You can avoid the issue by using an indirect method:
documentclass{article}
usepackage[first=0, last=1]{lcg}
newcommand{newrandomvar}[1]{%
newcommand{#1}{}% be sure the name is not taken
rand
edef#1{arabic{rand}}% note edef to end up with the actual value
}
begin{document}
newrandomvar{var}
ifnumvar=1
We have a one.
fi
ifnumvar=0
We have a zero.
fi
end{document}
A “more modern” version.
documentclass{article}
usepackage{xparse}
ExplSyntaxOn
NewDocumentCommand{newrandomvar}{m}
{
tl_new:N #1
tl_set:Nx #1 { int_rand:nn { 0 } { 1 } }
}
NewExpandableDocumentCommand{vartest}{mmm}
{
int_compare:nTF { #1 = 0 } { #2 } { #3 }
}
ExplSyntaxOff
begin{document}
newrandomvar{var}
ifnumvar=1
We have a one.
fi
ifnumvar=0
We have a zero.
fi
We have a vartest{var}{zero}{one}.
end{document}
Answered by egreg on August 27, 2021
A "more modern" version should look like this:
ifcase pdfuniformdeviate2 We have zeroor We have onefi
The pdfTeX primitive pdfuniformdeviate
and TeX primitive ifcase
are used here.
The pdfuniformdeviate <number>
expands to a random number from 0
to <number>-1
.
Answered by wipet on August 27, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP