1

I'm trying to generate some quasi random numbers to feed into a monte carlo simulation. I'm using bash. I seem to have hit a syntax error which I've narrowed down to being in this bit of code.

randno4=($RANDOM % 100001)
upper_limit4=$(echo "scale=10; 1*75.3689"|bc)
lower_limit4=$(echo "scale=10; 1*75.1689"|bc)
range4=$(echo "scale=10; $upper_limit4-$lower_limit4"|bc)
t_twall=`echo "scale=10; ${lower_limit4}+${range4}*${randno3}/100001" |bc`
echo "$t_twall"

Does anyone know why I the below output and not a value between 75.3689 and 75.1689 as that is what I would be expecting?

(standard_in) 1: syntax error
14
  • 1
    randno4=($RANDOM % 100001) is not arithmetic evaluation. That will create a randno4='([0]="25649" [1]="%" [2]="100001")' array. Perhaps you meant randno4='$(($RANDOM % 100001))'? Commented Nov 25, 2014 at 19:27
  • 1
    That first line is fine. It just doesn't do what you think it does. Run that line and then run declare -p randno4. Then try echo "$randno4" vs. echo "${randno4[1]}". Commented Nov 25, 2014 at 19:28
  • 3
    I believe the actual error here is from bc because of the randno3 typo. Commented Nov 25, 2014 at 19:29
  • 1
    The bash man page explains the range of RANDOM. It is documented as "a random integer between 0 and 32767". Commented Nov 26, 2014 at 0:28
  • 1
    The man command should be pretty much the first Linux command you learn. Here's the bash man page Commented Nov 26, 2014 at 6:42

1 Answer 1

6

The first line should looks like :

randno4=$((RANDOM % 100001))

(( )) is bash arithmetic, with the leading $ , the value is substituted : $(( ))

When you wrote

randno4=( )

you try to feed an ARRAY with a arithmetic expression with the wrong syntax.

See http://wiki.bash-hackers.org/syntax/arith_expr

And finally, like Etan Reisner said, You also use $randno3 in the t_twall assignment line which is undefined

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

2 Comments

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
This is correct for what it is covering (which is why I covered it in my comment) but this isn't the actual problem. That is fixing this does not fix the parsing error. The parse error is due to the $randno3 typo.

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.