text:
# What is the ideal way of emulating a full dice set using a single d20?

Imagine you are trapped in a post-apocalyptic world and only have a single d20 at your disposal, nothing else whatsoever. What is the ideal way of emulating all other common dice types (d4, d6, d8, d10, d12, d%) using just this d20 and arbitrarily complicated math?

I realize there's an easy way to make due with a single d6 (using the same d6 also for a coin-like mechanic), but I was wondering if this also works with a d20, and what the criteria are for this to work with a dN, if there is any research on the matter.

Let me preface this by defining a few pointers:

"ideal" = as few d20 rolls as possible.

"emulating" means mapping output from one or more d20 rolls to whichever die you want to emulate, while maintaining statistical accuracy - each possible output for the desired die must be equally likely.

"to map" a number X to an interval [1; B] means to apply an operation of the following form:

$$dB = X - B \times \textbf{int}\left[\frac{X - 1}{B}\right]$$

where the int[] operation demands rounding down (truncation, since the argument will never be negative for the given problem).

Here's what I have so far, in order of complexity:

Single roll $$\X\$$: d10 = $$\[X]\$$ if $$\[X \leq 10]\$$, else: $$\[X - 10]\$$

Single roll $$\X\$$: d% is equivalent to d10.

Single roll $$\X\$$: $$\\textbf{d4} = X - 4 \times \textbf{int}\left[\displaystyle{\frac{X - 1}{ 4}}\right]\$$

Two rolls $$\X\$$, $$\Y\$$: d8 = $$\[X]\$$ if $$\[X \leq 8]\$$, or $$\[X - 8]\$$ if $$\[9 \leq X \leq 16]\$$. Alternatively, for $$\[X > 16]\$$, d8 = $$\[Y]\$$ if $$\[Y \leq 8]\$$, or $$\[Y - 8]\$$ if $$\[9 \leq Y \leq 16]\$$. Alternatively, if both $$\[X > 16]\$$ and $$\[Y > 16]\$$, d8 = $$\[X - 16]\$$ if $$\[X+Y]\$$ = even, else: $$\[X - 12]\$$.

Three+ rolls $$\X\$$, $$\Y\$$, $$\Z\$$: $$\\textbf{d6} = X - 6 \times \textbf{int}\left[\displaystyle{\frac{X - 1}{6}}\right]\$$ if $$\[X \leq 18]\$$. If not, check the same for $$\Y\$$. If not, check the same for $$\Z\$$. If $$\\left\{X, Y, Z\right\}\$$ in $$\\left\{19, 20\right\}\$$ (which has a 1/1000 chance of happening), map the combination to $$\[1;6]\$$. However, I don't think it is possible to reliable get this mapping even when adding more and more dice rolls. Of course, it will get vastly unlikely rather quickly, but there does not seem to be a reliable way of using binary values to map to 6 reliably, seeing as it is a product of two primes. What is the lowest number of dice rolls required to achieve a 100% successful outcome, if it is possible at all?

The same issue applies to the d12, which can be constructed trivially from a d6 by rolling a d20 like a coin toss, then either using the initial d6 value or d6+6. This might not, however, be the ideal solution for this.

I would greatly appreciate any insight into the matter, as this has kept my mind busy for quite some time now. I'm pretty sure it cannot be reliably done for the d6 and d12, but I would appreciate any kind of closure or proof you peoples might be able to provide!

• Are you allowed to write on your d20? Sep 30 '20 at 13:31
• Would that change anything? I'd be happy to allow it if it helped tackle the problem in any way. I just realized that you might be able to introduce 3 directions for each roll that way - if that was your line of thought, the orientation of the number with respect to a fixed point might suffice? It wasn't what I originally had in mind. But I like the idea. I guess in the scenario I proposed here, more of a mathematical construct, you wouldn't be able to write on it. Sep 30 '20 at 14:07
• Related on using d6's for emulation: Is it possible to emulate common polyhedral dice rolls using just a d6, and if so, how? Sep 30 '20 at 14:47
• Why are you trying to play D&D alone when you're naked and stuck in a post-apocalyptic world with nothing but a single D20? Shouldn't you be trying to find food and shelter?
– J...
Oct 1 '20 at 12:46

## Emulating a d6 using a fixed number of d20 rolls is impossible.

Of course, as the other answer points out, it is possible to do so if we take into account more than just the rolled result, such as its orientation, but let's ignore that for a moment.

You rightly say that we can emulate a d6 with a d20 by mapping 1-18 to the d6 and rerolling on 19 or 20. This works, but this could in theory go on forever if we keep rolling above 18.

So, why is it impossible? As you said it has something to do with factorization. A d6 is impossible to create with a d20 not because it is the product of two primes, but rather because it has a prime factor which is not present in the prime factorization of 20. Firstly, note that the reason that we can't emulate a d6 with a single d20 is because 20 is not divisible by 6. Now, the prime factorization of 6 is $$\2 \times 3\$$, and that of 20 is $$\2^2 \times 5\$$. If we roll $$\n\$$ d20s, this gives a total of $$\20^n\$$ possibilities. Because multiplication is the same as adding the prime factors, $$\20^n\$$ will have $$\n\$$ times the factors:

$$20^n = 2^{2n} \times 5^n$$

That is, regardless of the amount of times we roll a d20, the total amount of possible results will never have a prime factor other than 2 or 5, and will therefore never be divisible by 3. Because every outcome is equally likely, there is therefore no way of distributing these outcomes over the faces of a d6 such that all 6 possibilities are equally likely.

More generally, a dX can emulate a dY if and only if X has all prime factors that Y has. Therefore, a d20 cannot emulate a d3, d6, d12 or d35, but it can emulate a d8, d10 or d4294967296.

## Example of emulating a d8 with a d20

If we wish to emulate a d8 with a d20, we first note that 20 is not divisible by 8. This is because 8 has three 2s in its prime factorization, and 20 has only two. However, $$\20^2\$$ has factorization $$\2^4 \times 5^2\$$, which encapsulates the prime factorization of 8, and therefore we need only two d20 rolls.

Now, all we needed from one of those rolls was a single factor 2, so we can use one of them as a coin flip. Therefore, we can roll the first d20 and if it lands on the top half (11-20), we take something from the top half of the d8 (5-8), and similarly for the bottom half (1-10) -> (1-4). Then we only have to divide the other d20 in four categories: (1-5) -> (1 or 5); (6-10) -> (2 or 6) and so forth.

Note that this is only an example, and there are plenty of ways to emulate a d8 with two d20s. All you have to do is ensure that out of the 400 possibilities with two sequential d20s, 50 of those possibilities are assigned to each of the 8 target numbers, which is equivalent to cutting the space equally in two a total of three times.

• Re "More generally, a dX can emulate a dY if and only if X has all prime factors that Y has.", So the smallest singular die that can emulate a standard set (d4,d6,d8,d10,d12,d20,d100*) is a d(2*3*5) = d30. All hail the new d30! It would be simpler with a d(2*2*2*3*5*5) = d600, though. (600 is the smallest number evenly divisble by the 4,6,8,10,12,20,100*.) [* A standard 7-dice set has two d10 dice to allow rolling a d100.] Oct 2 '20 at 7:33
• There's a more elegant way of phrasing this: you can simulate a roll of a dX with a bounded number of rolls of a dY if 1/X written in base Y terminates. (And as a bonus, the number of digits after the decimal point is the upper bound on the number of rolls needed.) Oct 3 '20 at 0:18
• Oct 3 '20 at 5:47

### An Icosahedron has 12 vertices.

Since an icosahedron has 12 vertices, all we need is a method for identifying the vertex which corresponds to a particular result.

### Orientation

Each face of a d20 is a triangle, so we can easily determine which vertex is the result based on its orientation relative to us. Simply take the vertex that is the furthest away or "on top" as the resulting vertex. If two vertices are on top, take the bottom. Maybe this isn't perfect, it will require a bit of a judgment call, but it should be a pretty clear result all of the time. To mitigate this, we can fashion a dice tray with ruled lines to help us make that judgment.

### Determining the result

Now we just have to determine the result. This will be a little tedious, but we can get it done by writing down and consulting the following table. I constructed this table based on one of my d20s, but you can construct your own if it is different, it will still work.

Once you have chosen your vertex, map the vertex's corresponding faces to the left most column of the table to get your d12 result. A d6 result is had by dividing the d12 result by 2 and rounding up. $$\begin{array}{|c||c|}\hline \text{Result} &\text{Vertex Faces}\\\hline 1&1,5,7,13,15\\\hline 2&1,3,7,17,19\\\hline 3&1,9,11,13,19\\\hline 4&2,8,10,12,20\\\hline 5&2,4,14,18,20\\\hline 6&2,5,12,15,18\\\hline 7&3,6,9,16,19\\\hline 8&3,8,10,16,17\\\hline 9&4,6,9,11,14\\\hline 10&4,5,11,13,18\\\hline 11&6,8,14,16,20\\\hline 12&7,10,12,15,18\\\hline \end{array}$$

### Example 1

So I rolled a d20 on one of my character sheets at DnDBeyond. Here is the result:

It is easy to see which vertex is "on top", so that vertex corresponds to {6,8,14,16,20}, which gives us a result of 11 on the table.

### Example 2

Here is a result where there is no clear "on top" vertex:

Here we choose the bottom vertex, which has faces {4,5,11,13,18} which gives a result of 10 on our table.

### The d8.

For the d8, first, convert your roll to a d4 by 1+(d20 modulo 4). Then, if the vertex at the top of the result number is away from you, add 4, else keep the d4 result.

User Rayllum came up with this solution and first communicated it to me in chat. He has since included it in their answer here, and have presented other solutions to the problem here. Go give his answers some love.

• Comments are not for extended discussion; this conversation has been moved to chat. Oct 2 '20 at 13:01

To directly implement a d6 or a d12, you can increase your d20 to a d60, by using the fact that

### Every face of a standard d20 has 3 distinctive vertices.

Looking at an example face, it is seen that the number defines the 'up' direction, as well as 'left' and 'right':

Therefore, the three vertices of a face can be distinctively described as "upper vertex", "left vertex" and "right vertex".

After the die is rolled, you look not only at the rolled number, but also which of the three vertices is furthest away from you.

• If the "upper vertex" is furthest away from you, use the rolled number as-is.
• If the "right vertex" is furthest away from you, add 20 to the rolled number.
• If the "left vertex" is furthest away from you, add 40 to the rolled number.

Then, de facto you have a d60. This allows for a direct implementation of a d12 (by dividing the numbers 1-60 into 12 partitions of the same size).

Alternatively, using the formula of the question:

Single roll $$\X\$$: $$\\textbf{d12} = X - 12 \times \textbf{int}\left[\displaystyle{\frac{X - 1}{ 12}}\right]\$$

Similarly for other factors of 60, e.g. 6, 15, 30.

Thanks to Thomas Markov and Someone_Evil for their contributions to this answer.

# By putting the d20 in your pocket

You don't need a die to emulate a die. Have the GM secretly choose a whole number. Have the player rolling declare some other whole number. Add the two together and then take the modulo of that sum by the size of the die to be emulated.

I've done this for years on account of being poor and not always having internet until recently. While it can take a little bit for players new to the system to learn how to pick numbers well (c.f. How to Win at Rock Paper Scissors), over time play approximates a fair die quite well, and it only ever takes one "roll".

• Wouldn't there be an issue where since no rolls are performed then the players might think the GM is being biased? Additionally the GM might think the same and not want to pick arbitrary numbers on the base of: oh hey I don't want to accidentally TPK so I should only do high numbers. Oct 1 '20 at 2:27
• @TheGrandJ The GM picks first for that reason. If you can't trust your GM for some reason, you have them write it down, or tell another player, but in my experience as long as the GM actually picks a number when it is their turn, it works fine-- most people who can't be trusted also suck at GMing. Also high numbers don't make good rolls. Oct 1 '20 at 2:54
• high numbers don't increase or decrease any chances. gm: chooses 95. player: chooses 15. result is 110. emulating a d20 is 110 % 20 = 10, so the roll was a ten Oct 1 '20 at 15:31
• I upvoted for uniqueness, but I have to agree with @TheGrandJ. Even if you aren't trying to be biased, if you know your players and know what numbers they are likely to pick, you will still have a subconscious inclination to pick numbers the complement or contrast those numbers. And if you are writing them down, rather than waste paper and pen(cil)s spent the buck to buy a d20. Oct 2 '20 at 0:15
• Humans are terrible random-number generators, although I expect combining two bad random numbers via sum and modulo helps a lot. (e.g. humans will rarely pick the same number twice in a row because that seems "not random"). Fortunately for D&D, the way we use them is often pass/fail thresholds or just damage totals, so many measures of statistical quality are probably less important than for a physics simulation / computational experiment. Oct 2 '20 at 3:32

In theory, you can simulate any die if you

### Think of your d20 as a compass.

The idea is to split $$\360^\circ\$$ into N even parts and let the "compass" select a part. (Similarly to a Twister spinner).

To simulate a dN, you roll the die and ignore the value of the number rolled. Instead you look where the "upper vertex"1 points to. Then, take the angle $$\ \alpha \$$ between the direction 'towards you' and your "upper corner" direction. E.g. if the "upper corner" points away from you, then $$\ \alpha = 180^\circ\$$; if the "upper corner" points to your right, then $$\ \alpha = 270^\circ\$$.

For exactly one integer $$\ X \$$ you have $$\(X-1) \cdot \frac{360^ \circ} N \leq \alpha < X \cdot \frac{360^\circ} N\$$. That $$\ X \$$ is your "rolled" number.

E.g, if $$\ N=4\$$, then any roll with "upper vertex" direction $$\\alpha\$$, where $$\1 \cdot 90^ \circ \leq \alpha < 2 \cdot 90^\circ \$$, results in the "rolled" number $$\ 2 \$$.

While this approach is very theoretical and in practice hardly applicable for large $$\ N\$$, it actually can be used in practice to

### Roll the d8 in one throw

Roll the d20 and use the rolled number as it would be done for a d4. Then, if the upper corner faces you (50% chance), add 4.

Generalized: To simulate a dN with a d20, calculate the greatest common divisor: $$\ g = gcd(N, 20)\$$. Then (if $$\g < N\$$), apply the compass-method to get a d$$\ \frac N g \$$ dice. Use the rolled number of the d20 to simulate a d$$\ g\$$.

Combining the d$$\ \frac N g \$$ and the d$$\ g\$$ yields a d$$\ N\$$

1See my other answer for the definition of "upper vertex".

• Alright, very good - now I get what you meant. Excellent point, and this is actually swifter than what I came up withfor the d8! Though I think in the context of a d12 roll this still looses to vertices in terms of simplicity, simply because measuring that angle would be rather difficult in practice. For a d12, you could look at the direction of the number to [1;6] and then use odd/even to either use the straight number or add 6 - I suppose that would make it easier. Sep 30 '20 at 20:17
• Yep, for large N this is a purely theoretical approach. For the d12 you can even go down to [1;3] for the direction and use the d20-result to decide whether to add 0, 3, 6 or 9. Sep 30 '20 at 20:21
• The previous two comments refer to an older version of this answer. To improve readability, the feedback & explanations of these comments are now included. Sep 30 '20 at 22:43
• Sometimes the die angle is going to be too close to the cutoff to judge, so it's effectively "cocked" and you have to reroll. As I showed in my answer, the expected number of rolls for the simple d20 / 2 round up, discarding 17..20, is 1.25 d20 rolls per d8. That's only slightly more than I'd expect from this method, but still interesting idea. Oct 2 '20 at 3:35
• @PeterCordes In practice you can still say: If it's too close to judge, take the higher number (A variant of Example 2 of Thomas Markov's answer). In the end, similarly to any sports "in- or out-of-field" case, you have to make a decision. Reading your comment actually gave me an idea on how to bring 1.25 down to 1.2 - I'll write it below your answer for readability. Oct 2 '20 at 10:35

Summary:

• Rolling and discarding averages fewer than 2 d20 per any other die, even d12. This is good for time and the stated criterion of number of rolls.
• Divide and round up is easier than actually working through your formula, and maybe easier than doing the modulo-like operation that's equivalent to your formula, except for d10 where you just take the trailing digit. This is more ideal for time, same number of rolls.
• idea from @superb rain in comments, not yet incorporated into this answer except for d4: often 1 player needs to roll multiple d6s or d8s (or d12s) in the same turn. A single d20 can give us a d8 and a d2 result without correlation, for example, letting us chain rolls by giving us a d8 output and some leftover entropy. With clever math, we can even reduce the number of d20 rolls per d8 below 1 when rolling multiple d8s. If someone wants to write this up as a new answer, I'll link to it here.

Discarding random samples is the standard way of avoiding bias when creating a uniform distribution from an RNG that generates a larger range than what you want, and the range isn't an exact multiple1. It's simple, easy to remember and understand, and probably quick to do in practice.

But how many rolls will we need on average with the simple re-roll method, e.g. discarding 19 and 20 when trying to roll a d6? Expected number of rerolls for simple sampling, discarding and rerolling 2 out of 20 numbers for a d6 (20 mod 6=2), 4 out of 20 for a d8 (20%8=4), 8 out of 20 for a d12 (20%12=8).

• d4: 1.0
• d6: sum((2/20)^n, n=0..inf) = 1.11111...
• d8: sum((4/20)^n, n=0..inf) = 1.25
• d10: 1.0
• d12: sum((8/20)^n, n=0..inf) = 1.6666...

These are all less than 2, even for d12. Any method that always rolls 2 dice is on average more rolls than rerolling. In the worst case for rerolls (d12), you don't have to do any math (just take the 1..12 result from the d20) so the total time spent to get a number is still not bad.

The chance of rolling 19 or 20 is 1 in 10. The chance of doing it again is 1/100, etc. The series 1/10 + 1/100 + 1/1000 + ... converges to 0.1111... extra d20 rolls per roll d6 roll, if I have the logic correct.

@Rayllum suggests in comments that instead of just discarding, switch strategy. e.g. for d8, on 17..20 use that as a d4, then the next roll determines whether to add 4 or not. i.e. the 2-roll d4 + 4*d2 strategy suggested in another answer. This reduces the average number of rolls for a d8 to 1.2, and sets a hard upper bound of 2. Similar tricks are possible for other dice.

But at least you don't have to do any math when you reroll, only on the one that's eventually in the right range. Rerolls are "cheaper" than other multiple-roll strategies because they can be done quickly with little mental effort, and uses the die "as intended" with no need to judge angles, just read the face. You do still need to do math at the end on the one die result, but that can be simpler than a formula that involves 2 inputs and larger intermediate values.

A rare long string of high d20 rolls might be amusing itself, or might just be frustrating ("where were these rolls for my attacks / saving throws / checks?")

Possibly some players who haven't overcome the gambler's fallacy would be frustrated that they're "wasting" all their high rolls by having to discard them. Discarding low rolls and shifting the mapping would make the math slightly less simple (1 extra subtraction step at the start), but might make some players happier (than discarding high rolls).

## Frame challenge: time, not just number of rolls, is probably the real concern

Clever outside-the-box answers have suggested using other properties of dice / angles, but some of them might make each roll take longer (e.g. judging the angle and/or consulting a lookup table of vertices).

Minimizing the average time to result is probably a better real-world goal than minimizing number of rolls. This part is a frame-challenge based on your post-apocalypse premise. The actual math question of finding minimum-rolls is also interesting.

With time in mind, let me suggest a simpler formula for mapping d20 rolls to smaller ranges. Your formula based on floor $$X - B \times \left \lfloor{\frac{X-1}{B}}\right \rfloor$$
is equivalent to 1 + (x-1)%B, a remainder from 1..B instead of 0..B-1. e.g. for B=4, it goes 1,2,3,4, 1,2,3,4, etc. I think it would be easier to directly use quotient rounded up ("ceiling").

$$\left \lceil{\frac{X}{5, 3, \tt or\ 2}}\right \rceil$$

This has the benefit for humans that higher numbers on the d20 are higher numbers on the d4 / d6 / d8 / d10 / d12.

e.g. for a d4, it's fairly intuitive to see where your number falls in the four ranges 1-5, 6-10, 11-15, 16-20. This works out nicely because 5 is a factor of 10, the number base we're used to using. Or just think of it as d20/5 round up.

Unfortunately we can't do it both ways on the same d20 to get 2d4 from one roll. (Unless you're rolling a lot of d4s and don't mind the correlation). 1 on the ceil(x/5) makes 1 on the 1+(x-1)%4 twice as likely as other results. Same with other numbers. (A different mapping could give opposite correlation, making rolls more likely to tend towards the average instead of away). You could do d20/4 and d20%4 for 2 independent d4 results, or just 1 if the roll was 17..20. With 2 players looking at the same d20 roll, one can total the the 1 + (x-1)%4 in their head, and the other can total the ceil(x/4), saving time for a player to roll magic missile damage or a healing potion.

For a d6, d20/3 round up is probably not as intuitive for most people, but I expect it's something you can quickly get good at. (Unless 5e mechanics of rounding down for damage resistance leads to frequent mistakes...) You could write down a table which is easy to visually search because d20 input and d6 output are both in ascending order.

For a d8, divide by 2 round up (and discard rolls 17..20). Or use your formula, which amounts to subtracting 8 or not for the high half of the acceptable range. That's also fairly simple and avoids "divide by 2 round up" which is very close to, but different from, standard 5e divide by 2 round down damage resistance. It probably comes down to experience which is mentally easier overall. Or discard 1 and 18..20, then divide by 2 round down.

For a d10, your way amounts to ignoring the leading digit (treating 0 as 10) which should be very quick and intuitive (and less risk of error) than dividing by 2 round up. Also avoids conflicting number-memory for damage resistance = divide by 2 round down.

For a d12, it's trivial math ("divide by 1"). The only cost is in a larger number of expected/average rerolls.

Footnote 1: In computer programming, rand() % 12 has only a tiny bias and can be "good enough" when rand() can produce numbers up to 2^32-1, but a huge bias when it produces numbers from 0..19. That would produce a random number from 0..11, but not uniformly distributed. The numbers 0..7 would come up twice as often as 8..11

Similarly, rand() / (RAND_MAX/12) has bad bias for small numbers like 12 because the range isn't evenly divisible into 12 equal-sized chunks.

I mention this only to point out that this problem is basically similar to one that's been studied extensively for computing. Doing it by hand, and with small ranges, makes the tradeoffs different.

A d20 roll has more information than a d6 roll (or any other of the smaller dice). Thus it should be possible to average less than one d20 roll for a d6 roll. To be more precise, log(6)/log(20)=0.5981 rolls of the d20 should suffice. How can it be less than one? Imagine emulating a d2 with a d4. Each d4 roll is worth two d2 rolls (take the d4 result divided by 2 as one d2 result, and take it modulo 2 for another), so d2 averages 0.5 rolls of d4.

For all requested dice with N sides:

 N   ideal d20 rolls
--------------------
4   0.46276
6   0.59810
8   0.69413
10   0.76862
12   0.82948

Emulating d2 with d4 is easy. How do we get such efficiency for emulating let's say d6 with d20? Let's roll the d20 twice right away. That gives us 400 possible different outcomes. That's 6 buckets of 66 outcomes each, and 4 leftover outcomes. Now:

• If the actual outcome falls into one of those 6 "good" buckets, we use the bucket number as a d6 result. But don't throw away where in the bucket we are! We can keep using this range of size 66 for further rolls.
• If the actual outcome is one of the 4 leftovers, we don't get a d6 result yet. But don't throw away which leftover we have! We can keep this range of size 4 for further rolls. Now grow it back up to over 1000 and try again until we do get a d6 result.

More technically:

• We'll keep two things: limit, and a number value in the range [0, limit). And every number in that range has equal probability to be value. Start with limit=1 and value=0.
• Whenever we want a new result for dN, first increase the size of the range to let's say limit≥1000. Do this by multiplying both limit and value with 20 and adding a new d20 roll result to value. Then apply the above case distinction, i.e., very likely get a dN result and retain a fairly large range, or very unlikely don't get a dN result and retain a fairly small range.

Note that for example for d4, in the very likely "good" case we not only get a d4 result, but also only shrink the range by about factor 4. While d20 rolls to grow the range grow it by factor 20. So two d4 results are shrinking the range more slowly than a one d20 roll grows it back up. This is how we average more than two d4 results per d20 roll. Or equivalently, how we average less than 0.5 d20 rolls per d4 result.

Results from doing that in Python, with one million rolls for each N:

       d20 rolls
N  average  ideal     average / ideal
----------------------------------------
4  0.46385  0.46276  1.0023523685865143
6  0.59994  0.59810  1.0030630049027711
8  0.69634  0.69413  1.0031713739604955
10  0.77008  0.76862  1.0019010821509053
12  0.83293  0.82948  1.0041577531922499

Note that the actually occurred averages are very close to the ideal ones. And: Remember that the "good case" not only gives us a dN result but also retains a much larger range. And we can make the good case more likely simply by keeping the range larger. I used what I said above, making limit≥1000. The larger you make it, the closer you get to ideal.

Full Python code (you can run it at repl.it, though there I reduced the rolls to 100,000):

from random import randrange
from math import log

def d20():
"""Return random integer from 0 to 19."""
global d20_rolls
d20_rolls += 1
return randrange(20)

value, limit = 0, 1
def dn(n):
"""Return random integer from 0 to n-1."""
global value, limit
while True:
while limit < 1000:
value = value * 20 + d20()
limit *= 20
multiple = limit - limit % n
if value < multiple:
result = value % n
value //= n
limit //= n
return result
value -= multiple
limit -= multiple

rolls = 10**6

for n in 4, 6, 8, 10, 12:
d20_rolls = 0
for _ in range(rolls):
dn(n)
average = d20_rolls / rolls
ideal = log(n) / log(20)
print('%2d' % n, '%.5f' % average, '%.5f' %  ideal, average / ideal, sep='  ')

• This is getting pretty far from what you'd want to actually do by hand / in your head. Interesting to work out the theoretical minimum for breaking up entropy into dX rolls, and a math method, but doing it by hand would be slower and more error-prone than other ways. e.g. for a d4, you might want to use results of 1..16 to get 2d4, or 17..20 to get 1d4. (x/5 and x%4 are somewhat correlated so we can't always get 2d4 from a single d20 with a simple fast mental calculation.) (I mentioned this 2d4 idea in my answer about actual practical methods you might truly use post-apocalypse.) Oct 3 '20 at 4:35
• @PeterCordes True, but they allowed "arbitrarily complicated math". Plus, post-apocalypse is hopefully far in the future, and until then our brain power is surely enough for this :-) Oct 3 '20 at 4:38
• Also interesting is the actual payoff for your method, i.e. if n d20 are rolled, how many d8 can de facto be used. If I calculated correctly, it's hard to get significantly better than 7d20 yielding on the average 9.78d8's, so 1.40 per roll. The next significantly better value is 16d20s with 22.80d8's (1.42 per roll) but sorting and dividing 16d20s seems not so practical. Oct 3 '20 at 10:07

To be able to emulate all of the required numbers, you need to be able to emulate d2, d3, and d5. For instance, to emulate a d10, you roll a d2 and a d5, and if the d2 comes out as 2, you add 5 to the d5 result. As all of the basic dice are multiples of 2, 3 and 5, with no other prime factors, this is what you require.

Similarly, to create d6, simply roll d2 and d3, and if the d2 is a 2, add 3. To create a d12, do a d6, then add 6 if a d2 is 2. A d4? Roll a d2, then if a second d2 is a 2, add 2.

With a d20, you can easily emulate d2 and d5 (also d4 and d10, which makes some processes easier). This leaves d3 as the only thing needing to be emulated.

This is not a trivial problem, and if no changes may be made to the die, and you need to be able to have absolute results (requiring no judgement calls) without the possibility of an infinite number of rerolls, then it won't be doable with a d20.

That said, there are ways around it.

Modifying the die

This is only reasonable if you only need d2, d4, d6, d8, and d12, but you can modify the die so that the 1 and 20 sides cannot be rolled - this could be achieved by adding mud or some other substance to prevent the die from stopping on 1 or 20. Then, for d3, if the number rolled is between 2 and 7, it's a 1, between 8 and 13, it's a 2, and between 14 and 19, it's a 3. For d2, simply look at whether the number is even or odd.

But this will destroy the d5 emulation.

Judgement call

As described by Thomas Markov in his answer, one could use the triangle shape of the d20 to create a kind of d3 (or d12) rolling mechanism. However, it relies on judgement. That is, you have to decide which corner is furthest from you... or if you can't decide it, you take the one nearest. That creates a situation where one could conceivably take any of three results, should it be a "too close to call" situation.

It looks like it's very close to being a "pointing down" position? Move your head ever so slightly so that the one you want is at the top, or position yourself so that they're equal and then take the one at the bottom.

So long as all players are honest, the system will work fine, of course.

Possibly Infinite Rolls

This one is a little simpler, but has its own drawbacks. Roll the d20. If it's a 19 or 20, roll again. Otherwise, take the value mod 3 (or count how many sixes it takes to get it down to between 1 and 6 - a 15 is subtracted twice (15 -> 9 -> 3), so it's a 2).

This does not rely at all on modifying the die, and is guaranteed to produce a fair d18 (which gives d3 and d6 as ways to read it)... but there's no guarantee that you will stop rolling 19s and 20s. In realistic circumstances, it's highly unlikely that you will get stuck in such a loop for more than a few rolls... but not impossible.

Don't use the d20 as a die

There are other ways to produce a d3 result. As noted by Please stop being evil, with two people choosing numbers, they can be combined in a way that effectively creates randomness. The d20 itself can be used to ensure fairness on this - simply put, the GM chooses 1, 2, or 3. She then positions the d20, while shielding it, so that it shows the chosen number. The player then announces their number (1, 2, or 3), and the GM reveals the d20 value. Add them together, and subtract 3 if the value is above 3.

The same can be done for any d value below 20.

This will feel very random... but people have a tendency to avoid the extremes, so the probabilities won't actually be equal.

A Fairer Version

There is one way that you could conceivably get better fairness without using the d20 as a die. The GM holds the die by the 1 and 20 inside a bag or similar, and the player picks one of the "middle" sides - there are 12 sides that are reasonably accessible (assuming the GM's fingers invariably functionally block the three sides directly adjacent to the 1 and 20. Then use the same approach described in "modifying the die" to determine the d3 result.

In the absence of a bag, you can simply have the player close their eyes... but this requires additional trust, as there's nothing stopping the GM from rotating the die while the player's eyes are closed in order to guide the player's finger to the desired side.

Make a Hole

There is one last approach that could work well, but it requires the ability to alter your surroundings to some degree - You could make a small hole shaped to match the vertex of a d20. You roll without being able to see the result, then guide the die to the hole, so that it slots in, before looking. The vertex at the top can work as a d12 (as described by Thomas Markov in their table), which enables you to also emulate a d6, and thus you have all dice doable with the d20.

• Modifying it to not be able to roll 1 or 20 would probably bias towards the faces that border on those, not uniformly to all other faces. More importantly, if you're playing an RPG like D&D 5e, you need to still be able to roll it as a d20 very often! (Or you'd have to emulate a d20 in terms of what you can still roll.) Oct 3 '20 at 4:40
• @PeterCordes - that's precisely why I specified that it's only okay if you're not after one of the multiple-of-5 dice. Note that I speak of using it for d2 and d3 emulation, and that you then combine results from there - while there will be bias in the result if you treat it like a d18, there should be d2 and d3 symmetries in the probabilities, due to how the faces are arranged. This would only fail if, say, you had a die with all of the multiples of 3 directly adjacent to the 1 and 20. Oct 4 '20 at 10:01

Over a series of rolls Arithmetic coding requires on average the fewest real rolls per emulated roll. The basic idea is that every possible outcome from the real rolls as well as every possible outcome from the emulated rolls are mapped to a range of real numbers between 0 and 1; with the width of each range being equal to that outcome's probability. Note that we can save D20 rolls by just emulating the sum for each multi-die roll. In order to use simpler fractions: after each emulated roll we re-map both sets of ranges so that the outcome of the last roll is expanded to the range 0-1. For example if we want to emulate the rolls D6 and then a 3D8:

D6 ranges:
1: 0 - 1/6
2: 1/6 - 1/3
3: 1/3 - 1/2
4: 1/2 - 2/3
5: 2/3 - 5/6
6: 5/6 - 1
We roll a 6 on the D20, the range we are looking at is now 3/10 - 7/20.
The remaining possibilities on the emulated D6 roll are:
2: 1/6 - 1/3
3: 1/3 - 1/2
We roll a 14 on the D20. The range we are looking at is now 67/200 - 27/80.
The result is 3.

Now we begin emulating 3D8:
After remapping: the range we are looking at is 1/100 - 1/40
3D8 ranges:
3: 0 - 1/512
4: 1/512 - 1/128
5: 1/128 - 5/256
6: 5/256 - 5/128
7: 5/28 - 35/512
8: 35/512 - 7/64
9: 7/64 - 21/128
10: 21/128 - 15/64
11: 15/64 - 81/256
12: 81/256 - 13/32
13: 13/32 - 1/2
14: 1/2 - 19/32
15: 19/32 - 175/256
16: 175/256 - 49/64
17: 49/64 - 107/128
18: 107/128 - 57/64
19: 57/64 - 477/512
20: 477/512 - 123/128
21: 123/128 - 251/256
22: 251/256 - 127/128
23: 127/128 - 511/512
24: 511/512 - 1
Since the remapped range after the last roll is narrower than 0-1; we
can already eliminate most of the possibilities. The remaining ones are:
5: 1/128 - 5/256
6: 5/256 - 5/128
We roll a 19 on the D20.
The range we are looking at is now 97 % 4000 :- 1 % 40
The result is 6
If we emulate another roll: the we can remap the current range to 151/625 - 7/25

Using this method: an individual emulated roll may require more D20 rolls than some of the other methods; but other rolls in the same sequence will require fewer or none.

### It is possible to emulate a full dice set using only fixed number of rolls, but not with a d20.

If you wish to emulate a full dice set using a fixed number of rolls, you need 3 dice. The required dice are: a d10, a d6, and a 2d or "coin". You can omit the "coin" from the required dice if you are willing to use an even/odd result from the d10 or d6. However, omitting the coin does not decrease the number of rolls needed.

To use any two smaller die to emulate a bigger die, the formula is:

dX = (dA * B) - (dB - 1)
where X = A * B

Starting with only a d2 or "coin". You can emulate a d4 by doing two dice rolls:

d4 = (d2 * 2) - (d2 - 1)

You can confirm the results for yourself using this anydice link.

Using this formula, we can produce the following dice in 2 rolls:

d12 = (d6 * 2) - (d2 - 1)
d20 = (d2 * 10) - (d10 - 1)
or (d10 * 2) - (d2 - 1)
d100 = (d10 * 10) - (d10 - 1)

You can see that the d10 is required here, as the number of faces on both the d20 and the d100 are not divisible evenly by 6.

Lastly the d8, which requires 3 rolls in total since we have to emulate the d4 as shown above:

d8 = ((d4) * 2) - (d2 - 1)
where d4 = (d2 * 2) - (d2 - 1)

• This doesn’t answer the question. Sep 30 '20 at 21:43
• Hi Thomas. I realise I don't directly address the title of OP's question. When I answered the question, there were already several responses which did. However, the OP also asks: "I realize there's an easy way to make due with a single d6 (using the same d6 also for a coin-like mechanic), but I was wondering if this also works with a d20, and what the criteria are for this to work with a dN..."
– user66244
Sep 30 '20 at 22:02
• Add multiple dice to the question goes beyond answering what you can do with any single dice. Oct 1 '20 at 13:44
• Welcome to RPG.SE! Take the tour if you haven't already, and check out the help center for more guidance.
– V2Blast
Oct 2 '20 at 9:40

disclaimer: I am not a math genius whatsoever and this is not a mathematically correct method.

So my system is simple, say you want to replicate a d4, if you roll your d20 from 1 to 4 you don't have to do anything and you apply the roll as normal.

However if the roll is greater than 4 you subract 16 from it. And if the difference is negative you roll again until that difference is positive. This method will gain you eventually a random value between 1 and 4.

For a d6 you would subtract 14 if it is greater than 6. For a d8 you would subtract 12 if the number is greater than 8. For a d10 you would subtract 10 if the humber is greater than 10. For a d12 you subract 8 if the number is greater than 12.

You could also use this system to replicate other odd die such as a d15 or a d13 as long as you subtract any result above the die number by it's difference from 20.

Happy Rolling!

You want a d2? Roll a d20. Odd numbers are 2, anything else is 1.

Want a d3? Roll a d20. If it's 1, 2 or 3 - keep the number. If it's greater than 3 - reroll, until you get something between 1 and 3.

Want a D4? Roll a d20. If it's 1, 2, 3 or 4 - keep the number. If it's greater than 4 - reroll, until you get something between 1 and 4.

You want a d5? Roll a d20...

You see the pattern. No orientations, no gimmicky methods. Rerolling takes 2 seconds - don't make your life harder

• A method that can take theoretically infinite rolls is not ideal as requested. Jan 14 '21 at 13:01
• Why would you ever reroll when emulating a d4/d5? Jan 14 '21 at 13:22


text: I will show you how to do it in two different ways and discuss why I prefer one method over the other. When you run it like this, nothing will happen. powershell documentation: PowerShell.exe Command-Line This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0 If you want to check the space on a single drive, then you call this as you would expect: On the other hand, if you want to test multiple drives, you can pass an array of strings. In particular, this section: -File. I generally do not do this for variables within PowerShell scripts themselves (because in most cases I’m controlling how those variables are being used), but I almost always ensure typing of my parameter variables so I can have some validation over my input. Every DBA should have basic PowerShell skills. You can launch your terminal in a specific configuration by using the wt.exe command. The first and arguably (see what I did there) the easiest way to get command line arguments is to write something like the following: If you run this from within the PowerShell ISE by pressing F5, nothing interesting will happen. Running the Get-Sample.ps1 script without the -StartPath or -OutFile results in PowerShell prompting for the required missing piece of data. What if you don’t control the data being passed, and the passing program passes items in quoted strings? I will outline the preferred method below. This leads to typing of your parameter variables. For example, how would you enter a file path like C:\path to file\File.ext. He started working with SQL Server 4.21a in 1995 and has survived numerous upgrades. Save the following script as Named_Parameters_Example_3.ps1. For example, the /command expects that each script command is surrounded by double quotes, so that it is passed as a single command-line argument. Otherwise, because PowerShell processes the command first, the backtick will escape the backslash instead of the quote as intended. One nice ability of reading the arguments this way is that you can pass in an arbitrary number of arguments if you need to. To get arguments by name, we need to … A command-line argument or parameter is an item of information provided to a program when it is started. Active 6 years, 7 months ago. To make sure PowerShell executes what you want, navigate in the command line to the same directory where you will save your scripts. It supports multiple data inputs. I use this so often that I wrap this in its own function. There is another way of ensuring your users enter a parameter when it’s mandatory. You’ll notice it forces you to enter the servername because you made that mandatory, but it still used the default environment name of Odyssey. To specify a file path with a space inside it, you’ll need to “escape” it. The -Command parameter is used to specify commands to be executed on launch. (An interesting side note: if you do put a space after comma, it will still treat the list of drive letters as a single parameter, the comma basically eats the space.). You can do this by testing to see if the parameter is null and then prompting the user for input. And in this case, it will override the default parameter for the environment with Discovery, and it will prompt the user for the computer name. Save the following example as Unnamed_Arguments_Example_3.ps1. Hit tab to autocomplete and enter the word test or any other word you want, and you should see something similar to: Now if you hit enter, you will again see the word test echoed. Text (strings) or XML (serialized CLIXML), PowerShell 3.0+: Runs PowerShell in multi-threaded apartment (STA is default), PowerShell 2.0: Runs PowerShell in a single-threaded apartment (MTA is default), Leaves PowerShell console running after executing the script/command, Avoid loading of PowerShell profiles for machine or user, Sets output format for data returned from PowerShell. wt new-tab "cmd" ; split-pane -p "Windows PowerShell" ; split-pane -H wsl.exe wt --% new-tab cmd ; split-pane -p "Windows PowerShell" ; split-pane -H wsl.exe Any subsequent arguments should be treated as literals - just as with -File. Mostly used with, Specifies whether to start the PowerShell process as a. You can run this from the command line in multiple ways: It will do exactly what you think: use the passed in servername value of HAL and the default environment of Odyssey. Note that there are commas separating the drive letters, not spaces. (The scripts for this article can be found here.). Also, note that all the parameters are after the -file "path\to\the\ps1\file.ps1" [parameters]) Finally, the Start in (optional) field should be added like this: C:\Users\jortega\Desktop\ (without quotes) (If you don't know about PowerShell, please see the tip, "Introduction to PowerShell".) To start Powershell in version 2.0 and not display the copyright information, use the command below: PowerShell -version 2.0 -NoLogo Parameters can be passed by position or by name. Microsoft Scripting Guy, Ed Wilson, is here. Fortunately, like most languages, PowerShell permits the use of parameters, but, like many things in PowerShell, there’s more than one way of doing it. Command-line environments like the Windows Command Prompt and PowerShell use spaces to separate commands and arguments—but file and folder names can also contain spaces. I just created a new variable: After updating the script for the production environment, I then modified the subject line for any outgoing emails to include the new variable. To make sure PowerShell executes what you want, navigate in the command line to the same directory where you will save your scripts. It was a simple request, and I supplied a simple solution. You’ve probably already guessed that since $args is an array, you can access multiple values from the command line. Create and save the following script as Named_Parameters_Example_2.ps1. These days, when he's not busy with playing with SQL Server or spending time with his family, he can often be found underground caving or teaching cave rescue with the NCRC. To overcome this, you can pass arguments by named parameter. Viewed 2k times 2. Just to make sure that command works the way you are expecting it to. By default, PowerShell will use the position of the parameters in the file to determine what the parameter is when you enter it. And now I have a script to rewrite! If you do force the same parameter name twice, PowerShell will give you an error similar to: One question that probably comes to mind at this point is how you would handle a parameter with a space in it. At the time though, I wanted to do this in a better way, and not just for this variable, but also for the others I use in the script. You will notice that this combines both, a default parameter and testing the see if the$servername is null and if it is, prompting the user to enter a value. powershell -Command {Get-WinEvent -LogName security} In cmd.exe , there is no such thing as a script block (or ScriptBlock type), so the value passed to Command will always be a string. However, keep in mind if someone tries to call the same script with an actual string such as: It will return a gross error message, so this can be a double-edged sword. This lets PowerShell know that this is all one parameter. The automatic variable called $args allows you to access command line arguments when You can cycle through arguments in the$args collection by using a line like this: foreach ($i in$args) {$i} You can use the collection index number to reference individual arguments. Fortunately, there’s a better way to handle this using named parameters. Save the following as Named_Parameters_Example_7.ps1. Try chunking the entire argument list like so You can specify commands to executed on launch as a string. If you want to be a bit more explicit in what you’re doing, you can also pass the values in as an array: Note that in this case, you do have to qualify the drive letters as strings by using quotes around them. PowerShell should now pop up a little dropdown that shows you the available parameters. It will echo back FOO. Do not bother to enter the environment name. If you need to call a PowerShell script via a command line style prompt (maybe in a scheduled task or an external system like vCenter Orchestrator) there are a number of different options. Save the following script as Named_Parameters_Example_5.ps1. Generally, I find using named parameters far superior over merely reading the arguments from the command line. You can specify a file to a ps1-script to execute it's content on launch using the -File parameter. Running a Command with Command Line Arguments Welcome › Forums › General PowerShell Q&A › Running a Command with Command Line Arguments This topic has 4 replies, 3 voices, and was last updated 1 year ago by For another, it doesn’t provide the user with any useful feedback. To me, this is the best of both worlds. I am using a program called sonar-runner that you execute from the commandline, and you can pass optional parameters. If the program does not use the MS C/C++ runtime parser to parse command line arguments, then how it is parsed is entirely dependent on how the program implemented it. He's been a Director and later VP of IT at several startups including PowerOne Media, TownNews and Traffiq and now consults. He wanted any emails sent out to include the name of the environment. Powershell pass parameters to ps1 file How to pass command-line arguments to a PowerShell ps1 file , This article helps. In other words, PowerShell won’t let you enter the same parameter twice if you use tab completion. This may be a problem if you need to control the type of data the user is entering. wt.exe command line arguments. >PowerShell.exe -Command "(Get-Date).ToShortDateString()" 10.09.2016 >PowerShell.exe -Command "(Get-Date To me it is easier at that point to use the Windows PowerShell console instead. Fortnightly newsletters help sharpen your skills and keep you ahead, with articles, ebooks and opinion to keep you informed. Besides not having to remember what parameters the script may need, you don’t have to worry about the order in which they’re entered. Both are equally valid, so let's look at how each is done. Summary: Microsoft Scripting Guy, Ed Wilson, talks about using named arguments in Windows PowerShell functions. This ability, combined with the ability to read JSON files in a previous article should give you a great deal of power to be able to control what your scripts do and how they operate. For one thing, you can accidentally pass in parameters in the wrong order. You might have trouble remembering their names and perhaps their order. In addition, any script command argument that includes spaces is expected to be surrounded by double-quotes within the command … How to download latest artifact from Artifactory using Powershell script (v2.0 or below)? This will result in the exact same output as above, which is what you should expect: If you used tab completion to enter the parameter names, what you will notice is once you’ve entered a value for one of the parameters (such as –envname above), when you try to use tab completion for another parameter, only the remaining parameters appear. There, he majored in CompSci, but probably spent as much time hiking, canoeing, caving and rock-climbing as he did studying. As well as offering advanced IntelliSense-style code completion, full formatting options, object renaming, and other productivity features, SQL Prompt also offers fast and comprehensive code analysis as you type. Command line arguments ShareX CLI “File or URL path ” If it is file path then upload it, if it is URL then download it and upload it. You can still enter the parameter on the command line too: And PowerShell won’t prompt for the servername since it’s already there. For example in the normal windows commandline tool a call may look something like: To simulate that run the script with a slight modification: If you instead declare$maybeanInt as an [int] like you did $anInt, you can assure the two get added together, not concatenated. I generally have both open anyway. You can write a script block inside the string, but instead of being executed it will behave exactly as though you typed it at a typical PowerShell prompt, printing the contents of the script block back out to you. I was troubleshooting a problem where an existing system was failing with a command along the lines of this: Greg Moore is a graduate of RPI. Ask Question Asked 6 years, 7 months ago. I have a PowerShell script named LookForFiles.ps1. PowerShell Scripting Guide to Python – Passing Command-Line Arguments Prateek Singh , 2 years ago 0 3 min read 7051 Passing Command-Line Arguments in Python This is a case where you will need to run the saved file from the ISE Console and supply a value for the argument. Command-line parameters that include space(s) must be surrounded by double-quotes: winscp.exe /ini ="C:\Users\martin\Documents\myconfig.ini" To use the double-quote as a literal, use two double-quotes sequentially. Consider why this may be important. Save the following as Named_Parameters_Example_6.ps1. Multiple semicolon ;-separated statements may be executed. In unnamed parameters method, you cannot have more control with inputs and powershel script itself look unclear to understand the process. You can add parameters and/or arguments after filepath to use them in the script. PowerShell "Streams"; Debug, Verbose, Warning, Error, Output and Information, PSScriptAnalyzer - PowerShell Script Analyzer, Path to script-file that should be executed and arguments (optional), -Command { - | [-args ] | [] }, Commands to be executed followed by arguments, Sets the execution policy for this process only, Sets input format for data sent to process. Powershell.exe Command Examples In this section I will give some Powershell.exe Command examples. Here are a couple of Options:--File-Command; Payload – File Syntax pwsh -File [file] Sample pwsh -File ./helloWorld.ps1 Payload – Command. The -Command parameter also supports a scriptblock input (one or multiple statements wrapped in braces { #code }. But that’s OK; PowerShell is smart. Command line arguments example in C Selected Reading UPSC IAS Exams Notes Developer's Best Practices Questions and Answers ... Computer Glossary Who is Who How to pass arguments in Invoke-Command in PowerShell? Per forum request, this article provides examples of how to access the packager's command line arguments as well as provide some useful functions to parse the contents. Name the script Unnamed_Arguments_Example_1.ps1 and run it with the argument FOO. Depending on the program, these arguments … Welcome › Forums › General PowerShell Q&A › Help: pwsh command won’t take command-line arguments This topic has 11 replies, 6 voices, and was last updated 10 … Name the script Unnamed_Argum… Using --%, so PowerShell will treat the rest of the command line as arguments to the application. With that said, any time you are struggling with command line arguments for an executable, use Start-Process -ArgumentList. Consider this one a PowerShell gem to keep Note that this is a fundamental, breaking change from how -Command functions today, which basically reassembles a PowerShell command line from all the arguments by mere string concatenation (with spaces) and then invokes the result based on PowerShell rules. A program can have many command-line arguments that identify sources or destinations of information, or that alter the operation of the program. There are a couple of ways to invoke Powershell in Linux. The answer is simple; you can wrap the parameter in quotes: With the flexibility of PowerShell and quoting, you can do something like: If you experiment with entering different values into the scripts above, you’ll notice that it doesn’t care if you type in a string or a number or pretty much anything you want. PowerShell Python command-line arguments Tagged: powershell, python This topic has 1 reply, 2 voices, and was last updated 2 weeks, 1 day ago by David Figueroa. Command Line Arguments The wt execution alias now supports command ... 9 Cmd Command Line Windows Terminal Preview v0.8 Release Kayla Cinnamon January 14, 2020 Jan 14, 2020 01/14/20 The release of the Windows Terminal preview v0.8 has arrived! This command-line string building is Text (strings) or XML (serialized CLIXML), Loads a pre-created console file that configures the environment (created using, Specify a version of PowerShell to run. While his focus is on the operations side of DBA, his interests include DR, performance and general IT problem solving. This is what you might expect, but say you had multiple parameters and wanted to make sure you had assigned the right value to each one. Save the following script as Unnamed_Arguments_Example_2.ps1. Param ([Parameter (Mandatory=$True)] [ValidateNotNull ()] $Var1, [Parameter (Mandatory=$True)] [ValidateNotNull ()] $Var2) Write-Host$Var1 Write-HOst $Var2 If you look at the help file about_Functions_Advanced_Parameters you will find this example: Get the latest news and training with the monthly Redgate UpdateSign up, (The scripts for this article can be found, "If this script were really going to do something, it would do it on$servername in the $envname environment", "There are a total of$($args.count) arguments", "Adding$anint to itself results in: $($anInt + $anInt)", "But trying to add$maybeanInt to itself results in: $($maybeanInt + $maybeanInt)", "$($args[$i]) has  $($diskdata.Used) Used and $($diskdata.Free) free", "$($drive1) has  $($diskdata.Used) Used and $($diskdata.Free) free", "$($drive2) has  $($diskdata.Used) Used and $($diskdata.Free) free", "$($drive3) has  $($diskdata.Used) Used and $($diskdata.Free) free", # don't bother testing for drive3 since we didn't even have drive 3, "$($drive) has  $($diskdata.Used) Used and $($diskdata.Free) free", How to Use Parameters in PowerShell Part I, How to User Parameters in PowerShell Part II, How to Use Parameters in PowerShell Part II, Copyright 1999 - 2020 Red Gate Software Ltd. You can pass in commands from the standard input by using -Command -. SQL Prompt is an add-in for SQL Server Management Studio (SSMS) and Visual Studio that strips away the repetition of coding. In this case, you only have the one parameter, param1. Sample of missing a required argument Providing the -StartPath results in successful completion of the script. One attempt to write this using named parameters might look like: As you can see, that gets ugly fairly quickly as you would have to handle up to 26 drive letters. Almost every PowerShell cmdlet can accept one or more optional parameters which can be supplied on the command line in the form -Parameter_Name Parameter_Value The name of the parameter is always preceded by a hyphen (-) The Parameter_value often needs to be provided in a … I need to start a PowerShell script from the command line and I use the following syntax: start powershell.exe -noexit E:\PowerShell\Myscript.ps1 It works fine. Use a normal command line (cmd) interface to run the command without the powershell bits. It soon became apparent that this was less than optimal when I needed to move a script from Dev\UAT into production because certain variables would need to be updated between the environments. And you will see your script echo back the word test. There may also be cases where you don’t want a default parameter, but you absolutely want to make sure a value is entered. This means that I try to use defaults. Stack Exchange network consists of 176 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. To write a string that runs a PowerShell command, use the format: " & { command }" -PSConsole File Load a PowerShell console file. Command Line Parameters in Powershell. If the program does not use the MS C/C++ runtime parser to parse command line arguments, then how it is parsed is entirely He is the author of: IT Disaster Response: Lessons Learned in the Field. @(10, 100, 1000, 10000, 100000) | ForEach-Object { $IterationTime = Measure-Command {$array = @() #make a fresh array 1..$_ | ForEach-Object { #We make Powershell count from 1 to the current value in the iteration 10, 100, 1000 You can pass parameters to a PowerShell script two different ways. Here is a full sample that I reuse in my scripts for installing MSI files. In PowerShell the command line arguments are the variable names used within the param () block. PowerShell execute command with arguments safely In my opinion this is the best way for executing external commands from PowerShell with arguments in a safe manner - via the use of an array to hold the arguments. Multiple semicolon ;-separated statements may be executed. To get username Environment::UserName; Syntax pwsh -Command "[command]" Sample Hello World Some options you can set are tab and pane arrangements as well as their starting directories and profiles. Recently I have been having some trouble using GnuWin32 from PowerShell whenever double quotes are involved. You can save a custom command as a shortcut and pin it to your taskbar to open your desired configuration. -Command You can specify commands to executed on launch as a string. You will get back results for the amount of space free on the drive letters you list. This means the following will work: Here’s where the beauty of named parameters shines. As you can see, you can enter as many drive letters as you want. Modify the Named_Parameters_Example_2.ps1 script as follows and save it as Named_Parameters_Example_4.ps1. This only works when calling PowerShell.exe from another Windows PowerShell-session. For example, the /command expects that each script command is surrounded by double quotes, so that it is passed as a single command-line argument. For example, save the following script as Unnamed_Arguments_Example_4.ps1. The first one is related to the "powershell.exe -file" command and the second one is the file parameter of the script. When running a script, I prefer to make it require as little typing as possible and to eliminate errors where I can. If the value of Command is a string, it must be the last parameter in the command , any characters typed after command are interpreted as the command arguments. Malicious Powershell Process - Multiple Suspicious Command-Line Arguments Help You must be ingesting data that records process activity from your hosts to populate the Endpoint data model in the Processes node. You must also be ingesting logs with both In this article, Greg Moore explains how to write a PowerShell script that takes parameters. Command line arguments are extra commands you can use when launching a program so that the program's functionality will change. The first and arguably (see what I did there) the easiest way to get command line arguments is to write something like the following: If you run this from within the PowerShell ISE by pressing F5, nothing interesting will happen. This is a case where you will need to run the saved file from the ISE Console and supply a value for the argument. Type in the same command as above but add a dash (-) at the end. Copy the following script and save it as Named_Parameters_Example_1.ps1. One area that reading the arguments is a tad easier is when you need the ability to handle an unknown number of arguments. Instead, it builds a command-line string itself and assigns it to the System.Diagnostics.ProcessStartInfo.Arguments property, which is a single string; the .ArgumentList property didn't become available until .NET Core 2.1. When I wrote this script, it was early in my days of writing PowerShell, so I simply hardcoded variables into it. The standard input can come from echo, reading a file, a legacy console application etc. To actually do this from inside the Windows PowerShell ISE, you have to pass the path to the script and the command-line arguments from the Windows PowerShell ISE immediate (or command) pane. Hopefully, this article has given you some insight into the two methods of passing in variables to PowerShell scripts. Arguments will be used as values for undefined/available script-parameters, the rest will be available in the$args-array, This modified text is an extract of the original Stack Overflow Documentation created by following, https://powershell.programmingpedia.net/favicon.ico, Amazon Web Services (AWS) Simple Storage Service (S3), Anonymize IP (v4 and v6) in text file with Powershell. The method works, but I would argue that it’s not ideal. Outline. Otherwise, because PowerShell processes the command first, the backtick will escape the backslash instead of the quote as intended. Pass arguments by named parameters. Grégory Schiro - PowerShell MVP - PowerShell & MOF Proposed as answer by Grégory Schiro Friday, June 4, 2010 12:22 PM Marked as answer by IamMred Friday, June 18, 2010 4:22 AM Recently I had a client ask me to update a script in both production and UAT. You should get: This isn’t much savings in typing but does make it a bit easier and does mean that you don’t have to remember how to spell Odyssey! Options. If you run the script from directly inside PowerShell itself, as opposed to the ISE, tab completion will still show you the available parameters, but will not pop them up in a nice little display. Was a simple request, and the passing program passes items in quoted strings SQL Server Management Studio ( )! Launching a program called sonar-runner that you execute from the command without the -StartPath or -OutFile results PowerShell! See your script echo back the word test and UAT the scripts for installing MSI files and. Means the following will work: here ’ s mandatory in its own function names! Script, it doesn ’ t let you enter a file to determine what the parameter is to. A couple of ways to invoke PowerShell in Linux filepath to use the Windows PowerShell Console.... Arguments—But file and folder names can also contain spaces the data being passed, the. As Named_Parameters_Example_4.ps1 skills and keep you informed -OutFile results in PowerShell the command (! File path with a space inside it, you can access multiple values from command. Input ( one or multiple statements wrapped in braces { # code } Question Asked 6,! Executed on launch using the -File parameter article can be passed by position or by name area that the!, but I would argue that it ’ s a better way to handle this using named.. You enter a parameter when it ’ s OK ; PowerShell is smart different ways discuss. Users enter a file to a ps1-script to execute it 's content on launch I find using named far. This in its own function open your desired configuration that alter the operation of the as! Navigate in the script well as their starting directories and profiles I would argue it. Path with a space inside it, you only have the one parameter the word.... Control with inputs and powershel script itself look unclear to understand the process ps1-script to execute it 's content launch!, so I simply hardcoded variables into it can be found here. ) - just with! To PowerShell ''. ) survived numerous upgrades a shortcut and pin it.. ( cmd ) interface to run the saved file from the command line ( cmd ) interface run. For installing MSI files own function will happen be a problem if you don ’ t let you enter file... Destinations of information, or that alter the operation of the parameters in the wrong order terminal in specific! Operations side of DBA, his interests include DR, performance and general it problem solving in! Determine what the parameter is used to specify a file path with a space inside powershell command line arguments, you access... Where I can guessed that since \$ args is an array, you can pass arguments by parameter! Variables to PowerShell scripts PowerShell know that this is all one parameter there he. Required missing piece of data the user is entering normal command line Director and later of... The repetition of coding escape ” it set are tab and pane arrangements as well as their starting and... Is on the drive letters you list from another Windows PowerShell-session simple request, and you will see your echo. As many drive letters as you can pass in commands from the ISE Console and supply a value the. Here. ) commands to be executed on launch using the -File parameter can pass arguments by parameter! Used with, Specifies whether to start the PowerShell bits passes items in quoted strings way to an... Here is a case where you will see your script echo back the word test v2.0 or below ) interface...

format: plain


text:
Article Contents
Article Contents

# A case study of optimal input-output system with sampled-data control: Ding et al. force and fatigue muscular control model

• * Corresponding author: Jérémy Rouot
• The objective of this article is to make the analysis of the muscular force response to optimize electrical pulses train using Ding et al. force-fatigue model. A geometric analysis of the dynamics is provided and very preliminary results are presented in the frame of optimal control using a simplified input-output model. In parallel, to take into account the physical constraints of the problem, partial state observation and input restrictions, an optimized pulses train is computed with a model predictive control, where a non-linear observer is used to estimate the state-variables.

Mathematics Subject Classification: 49K15, 93B07, 92B05.

 Citation:

• Figure 1.  Time evolution of the permanent control (thin continuous line) and sampled-data control for several values of the sampling period $T_s\in \{T/20, T/40, T/200\}$

Figure 2.  Evolution of $K_m$ for different initial conditions (case of $I = 10ms$)

Figure 3.  Relative error of the force for a well known and erroneous $K_m$ initial condition (case of $I = 10ms$)

Figure 4.  General MPC strategy diagram

Figure 5.  (left half plane) $E_s$ and force profile for applied amplitude and interpulse stimulation, (right half plane) Predicted $E_s$ and force using single move strategy to be optimized

Figure 6.  Evolution of $A$ and $\hat{A}$ for $I = 10$, $30\%$ error of $K_m$

Figure 7.  Evolution of $A$ and $\hat{A}$ for $I = 25$, $30\%$ error of $K_m$

Figure 8.  Evolution of $\tau_1$ and $\hat{\tau_1}$ for $I = 10$, $30\%$ error of $K_m$

Figure 9.  Evolution of $\tau_1$ and $\hat{\tau_1}$ for $I = 25$, $30\%$ error of $K_m$

Figure 10.  Evolution of $F$, $\hat{F}$ and $F$ mean value over $I$ for $I = 25$, $30\%$ error of $K_m$, $Fref = 250N$

Figure 11.  Evolution of the force for a reference force of $425N$ and different receding horizons $(3, 5$ and $10)$

Figure 12.  Evolution of the interpulse (control) for a reference force of $425N$ and a preditive horizon of $10$

Figure 13.  Evolution of the amplitude (control) for a reference force of $425N$ and a preditive horizon of $10$

Figure 14.  Evolution of the interpulse (control) for a reference force of 425N and a preditive horizon of 10

Figure 15.  Evolution of the amplitude (control) for a reference force of 425N and a preditive horizon of 3

Table 1.  Margin settings

 Symbol Unit Value description $C_{N}$ — — Normalized amount of $Ca^{2+}$-troponin complex $F$ $N$ — Force generated by muscle $t_{i}$ $ms$ — Time of the $i^{th}$ pulse $n$ — — Total number of the pulses before time $t$ $i$ — — Stimulation pulse index $\tau_{c}$ $ms$ $20$ Time constant that commands the rise and the decay of $C_{N}$ $R_{0}$ — $1.143$ Term of the enhancement in $C_{N}$ from successive stimuli $A$ $\frac{N}{ms}$ — Scaling factor for the force and the shortening velocity of muscle $\tau_{1}$ $ms$ — Force decline time constant when strongly bound cross-bridges absent $\tau_{2}$ $ms$ $124.4$ Force decline time constant due to friction between actin and myosin $K_{m}$ — — Sensitivity of strongly bound cross-bridges to $C_{N}$ $A_{rest}$ $\frac{N}{ms}$ $3.009$ Value of the variable $A$ when muscle is not fatigued $K_{m, rest}$ — $0.103$ Value of the variable $K_{m}$ when muscle is not fatigued $\tau_{1, rest}$ $ms$ $50.95$ The value of the variable $\tau_{1}$ when muscle is not fatigued $\alpha_{A}$ $\frac{1}{ms^{2}}$ $-4.0 10^{-7}$ Coefficient for the force-model variable $A$ in the fatigue model $\alpha_{K_{m}}$ $\frac{1}{msN}$ $1.9 10 ^{-8}$ Coefficient for the force-model variable $K_{m}$ in the fatigue model $\alpha_{\tau_{1}}$ $\frac{1}{N}$ $2.1 10^{-5}$ Coefficient for force-model variable $\tau_{1}$ in the fatigue model $\tau_{fat}$ $s$ $127$ Time constant controlling the recovery of $(A, K_{m}, \tau_{1})$
•  [1] T. Bakir, B. Bonnard and S. Othman, Predictive control based on non-linear observer for muscular force and fatigue model, Annual American Control Conference (ACC), Milwaukee (2018) 2157-2162. doi: 10.23919/ACC.2018.8430962. [2] J. Bobet and R. B. Stein, A simple model of force generation by skeletal muscle during dynamic isometric contractions, IEEE Transactions on Biomedical Engineering, 45 (1998), 1010-1016.  doi: 10.1109/10.704869. [3] L. Bourdin and E. Trélat, Optimal sampled-data control, and generalizations on time scales, Math. Cont. Related Fields, 6 (2016), 53-94.  doi: 10.3934/mcrf.2016.6.53. [4] S. Boyd and  L. Vandenberghe,  Convex Optimization, Cambridge University Press, 2004.  doi: 10.1017/CBO9780511804441. [5] C. R. Cutler and B. L. Ramaker, Dynamic Matrix Control: A Computer Control Algorithm, In Joint automatic control conference, San Francisco, 1981. [6] J. Ding, S. A. Binder-Macleod and A. S. Wexler, Two-step, predictive, isometric force model tested on data from human and rat muscles, J. Appl. Physiol., 85 (1998), 2176-2189.  doi: 10.1152/jappl.1998.85.6.2176. [7] J. Ding, A. S. Wexler and S. A. Binder-Macleod, Development of a mathematical model that predicts optimal muscle activation patterns by using brief trains, J. Appl. Physiol., 88 (2000), 917-925.  doi: 10.1152/jappl.2000.88.3.917. [8] J. Ding, A. S. Wexler and S. A. Binder-Macleod, A predictive model of fatigue in human skeletal muscles, J. Appl. Physiol., 89 (2000), 1322-1332.  doi: 10.1152/jappl.2000.89.4.1322. [9] J. Ding, A. S. Wexler and S. A. Binder-Macleod, Mathematical models for fatigue minimization during functional electrical stimulation, J. Electromyogr. Kinesiol., 13 (2003), 575-588.  doi: 10.1016/S1050-6411(03)00102-0. [10] R. Fletcher, Practical Methods of Optimization, A Wiley-Interscience Publication. John Wiley & Sons, Second edition., Ltd., Chichester, 1987. [11] J. P. Gauthier, H. Hammouri and S. Othman, A simple observer for non-linear systems Application to bioreactors, IEEE Trans. Automat. Control, 37 (1992), 875-880.  doi: 10.1109/9.256352. [12] R. Gesztelyi, J. Zsuga, A. Kemeny-Beke, B. Varga, B. Juhasz and A. Tosaki, The Hill equation and the origin of quantitative pharmacology, Arch. Hist. Exact Sci., 66 (2012), 427-438.  doi: 10.1007/s00407-012-0098-5. [13] R. Hermann and J. Krener, Non-linear controllability and observability, IEEE Transactions on Automatic Control, AC-22 (1977), 728-740.  doi: 10.1109/tac.1977.1101601. [14] A. Isidori, Non-linear Control Systems, 3rd ed. Berlin, Germany: Springer-Verlag, 1995. doi: 10.1007/978-1-84628-615-5. [15] L. F. Law and R. Shields, Mathematical models of human paralyzed muscle after long-term training, Journal of Biomechanics, 40 (2007), 2587-2595. [16] S. Li, K. Y. Lim and D. G. Fisher, A state space formulation for model predictive control, Springer, New York, 35 (1989), 241-249. doi: 10.1002/aic.690350208. [17] J. Richalet, A. Rault, J. L. Testud and J. Papon, Model algorithmic control of industrial processes, In IFAC Proceedings, 10 (1977), 103–120. doi: 10.1016/S1474-6670(17)69513-2. [18] H. J. Sussmann and V. Jurdjevic, Controllability of non-linear systems, J. Differential Equations, 12 (1972), 95-116.  doi: 10.1016/0022-0396(72)90007-1. [19] L. Wang, Model Predictive Control System Design and Implementation Using MATLAB, Springer, London, 2009. [20] E. Wilson, Force Response of Locust Skeletal Muscle, Southampton University, Ph.D. thesis, 2011.

Figures(15)

Tables(1)


text:
# function

• Mar 7th 2010, 12:19 PM
summerset353
function
g(x)= |_x_|

What do these brackets mean?
• Mar 7th 2010, 12:43 PM
southprkfan1
Quote:

Originally Posted by summerset353
g(x)= |_x_|

What do these brackets mean?

It's the largest integer less than or equal to x
• Mar 7th 2010, 12:49 PM
summerset353
would the derivative of |_x_| be equal to 1? Or is it different because of the brackets?
• Mar 7th 2010, 12:56 PM
southprkfan1
Quote:

Originally Posted by summerset353
would the derivative of |_x_| be equal to 1? Or is it different because of the brackets?

Well looking at x on the interval [0,1), g(x) = 0 for all x....
• Mar 7th 2010, 08:46 PM
Drexel28
Quote:

Originally Posted by summerset353
would the derivative of |_x_| be equal to 1? Or is it different because of the brackets?

Is the function even continuous? If you look at the function $f:(n,n+1)\mapsto\mathbb{R},\text{ }n\in\mathbb{N}$ with $f(x)=\left \lfloor x\right\rfloor$ then in fact $f(x)=1$. And so $f'(x)=0$.


text:
# Thread: ordered integer pair,s (x,y)

1. ## ordered integer pair,s (x,y)

(1) If $(1!)^2+(2!)^2+(3!)^2+.......................+(x!)^ 2 = y^2$. Then ordered integer pair,s of $(x,y)$ , where $(x,y)\in \mathbb{N}$

(2) If $(1!)^3+(2!)^3+(3!)^3+.......................+(x!)^ 3 = y^3$. Then ordered integer pair,s of $(x,y)$ , where $(x,y)\in \mathbb{N}$

2. ## Re: ordered integer pair,s (x,y)

(1,1) is one such ordered pair for both of those. I ran a check in Mathematica, and up to x=1000, there are no other valid pairs for either of them. You might try continued fractions...

$\cfrac{\cfrac{\cfrac{y^2-1}{2^2}-1}{\cdots}-1}{x^2} = 1$ (for part (1))

$\cfrac{\cfrac{\cfrac{y^3-1}{2^3}-1}{\cdots}-1}{x^3} = 1$ (for part (2))