1

A friend of mine has written a Warlords battle odds calculator in Matlab that I would like to replicate in Python 3. I'm not very experienced in Python and don't know Matlab at all, but I can sort of see what's happening in the Matlab code. This one line has me a bit confused though.

r1 = ceil((rand*10));

Is this asking for the ceiling of a random floating point number from 0-1, then multiplying by 10?

ghulseman
  • 125
  • 1
  • 1
  • 7
  • 2
    opposite, it's multiplying a random float-point number by 10, *then* taking the ceiling function – C.Nivs Apr 08 '19 at 19:20
  • Is that really MATLAB code? It should be valid in Python too – roganjosh Apr 08 '19 at 19:21
  • @roganjosh: Any sufficiently short bit of code is valid in any programming language. :) – Cris Luengo Apr 08 '19 at 19:46
  • @roganjosh I think for python you would need to import math, and then call it as math.ceil() ... similar idea for rand. (I'm sure you know this, so mentioning it for the benefit of future readers of this thread.) – a11 Apr 08 '19 at 21:36
  • @AlexS1 True. But you can also do `from math import ceil` so there isn't really anything in this that couldn't be valid python. The semi-colon is ignored – roganjosh Apr 08 '19 at 21:37

1 Answers1

0

rand gives a random number in the interval (0,1), so rand*10 gives a random number in (0,10) (with uniform probability). ceil((rand*10)) gives a random integer between 1 and 10 inclusive.

The corresponding Python is thus:

random.randint(1,10)

To make the above code work, you would need import random earlier in the script.

John Coleman
  • 51,337
  • 7
  • 54
  • 119
  • Unspecified, the interval is 0 and 1? That's what threw me. Thanks for all the responses. Apparently, I could have just run the code in Python and figured it out that way – ghulseman Apr 10 '19 at 14:18