1

I am in many ways extremely new to programming so thank you for putting up with my idiocy because I'm sure I am not asking this in the right way.

I'm having to use a linux machine and a lot of command line stuff for the first time in years. I need to do a Monte Carlo simulation using a cloud model that is written and ready to go. It has an input file that I need to vary set input values in to be generated using some kind of random number generator. My supervisor insists that I use BC to generate random numbers.

My understanding is that BC is a language. I have downloaded it using:

sudo apt-get install bc

Now I think I should try to write some kind of script that makes a copy of the original input file and then searches for the strings in the original file and replaces them with the strings I want it to use. I think I can do this with a shell script?

I do not understand how I can use bc and bash at the same time. If I enter a BC command will it just do it? Does BC execute shell commands? How does this work?

In your answer remember that I am just a lab monkey left with a computer who does not really understand anything about programming.

2 Answers 2

1

You can use bc within a shell script, for example

#!/bin/bash

# Generate random number between 0 and 9
RANDVAR=$(echo "$RANDOM % 10" | bc)
echo $RANDVAR

This simple script shows how you can assign a variable a name and use it later in the script. Anything in "$()" will be run, and the result assigned to the name (in this case RANDVAR). You can use this variable later in your substitution using, for example, sed.

Sign up to request clarification or add additional context in comments.

1 Comment

The number generated by taking $RANDOM modulo 10 will be biased and therefore unsuitable for Monte Carlo since the range of $RANDOM is 0 to 32767.
1

One way to interact between shell and bc :

$ echo "$RANDOM % 5" | bc

will print a random number in the range 0 to 4

$RANDOM is a pseudo random integer usable directly in your shell.

Note that double quotes are mandatory to use shell variables. With single quotes, the variables will be never evaluated.

After, you can do arithmetic if you need with and (( )) arithmetic operator :

value=$(echo "$RANDOM % 5" | bc)  # 0 10 4
((value*10))                      # value X 10
echo $value                       # display $value value
echo "scale=2; $value / 100" | bc # scale=display 2 decimal

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.