Splunk Search

How do I generate a random number between a specific range?

sravani27
Path Finder

Hi, How can I generate a random number between 1 to 20. I random() function doesn't allow to specify a range. please help

Tags (1)

PickleRick
SplunkTrust
SplunkTrust

One thing - in case of small ranges it might be negligible but if you want a random number from a big range (like between 0 and 1.5*2^30) performing a modulo on random() will not give you uniform distribution.

0 Karma

gbhatti
Engager

@PickleRick I was not aware of this. Thanks for pointing it out.

0 Karma

worshamn
Contributor

Building a bit on @richgalloway 's answer I believe this works and allows you to set the high and low range. I added just some extra fluff for testing, your eval line could just look line 4 with high and low replaced with your range:

| makeresults
| eval high = 100
| eval low = 10
| eval rand = round(((random() % high)/(high)) * (high - low) + low)
| eval inRange = if(rand <= high AND rand >= low, "True", "False")

gbhatti
Engager

@worshamn Kudos! Building on your solution I slightly simplified the math.

 

...
| eval rand = random() % (high - low + 1) + low
...

 

 

woodcock
Esteemed Legend

@ppablo_splunk , this one should get moderator-answered.

0 Karma

richgalloway
SplunkTrust
SplunkTrust

Try using the modulo operator. For example, ... | eval rand=(random() % 20) + 1 | ....

---
If this reply helps you, Karma would be appreciated.
Get Updates on the Splunk Community!

Index This | I am a number, but when you add ‘G’ to me, I go away. What number am I?

March 2024 Edition Hayyy Splunk Education Enthusiasts and the Eternally Curious!  We’re back with another ...

What’s New in Splunk App for PCI Compliance 5.3.1?

The Splunk App for PCI Compliance allows customers to extend the power of their existing Splunk solution with ...

Extending Observability Content to Splunk Cloud

Register to join us !   In this Extending Observability Content to Splunk Cloud Tech Talk, you'll see how to ...