diff options
author | kintel <kintel@b57f626f-c46c-0410-a088-ec61d464b74c> | 2010-10-31 02:51:11 (GMT) |
---|---|---|
committer | kintel <kintel@b57f626f-c46c-0410-a088-ec61d464b74c> | 2010-10-31 02:51:11 (GMT) |
commit | d479fca855688c92f4a9f72f4ec18d655c3b351d (patch) | |
tree | 56c6979cc6b28753c2b67e4b5ced49db45c6d365 /src/func.cc | |
parent | e0c5673e1bf965fbb1bbbef2562a54be1a3144a3 (diff) |
Added a rands() function that returns a vector of random numbers.
the function takes either 3 arguments or 4
rands(min,max,num)
or
rands(min,max,num,seed)
git-svn-id: http://svn.clifford.at/openscad/trunk@574 b57f626f-c46c-0410-a088-ec61d464b74c
Diffstat (limited to 'src/func.cc')
-rw-r--r-- | src/func.cc | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/src/func.cc b/src/func.cc index eb0afcd..6f7ff1c 100644 --- a/src/func.cc +++ b/src/func.cc @@ -124,6 +124,44 @@ Value builtin_sign(const Context *, const QVector<QString>&, const QVector<Value return Value(); } +double frand() +{ + return rand()/(double(RAND_MAX)+1); +} + +double frand(double min, double max) +{ + return (min>max) ? frand()*(min-max)+max : frand()*(max-min)+min; +} + +Value builtin_rands(const Context *, const QVector<QString>&, const QVector<Value> &args) +{ + if (args.size() == 3 && args[0].type == Value::NUMBER && args[1].type == Value::NUMBER && args[2].type == Value::NUMBER) + { + srand((unsigned int)time(0)); + } + else if (args.size() == 4 && args[0].type == Value::NUMBER && args[1].type == Value::NUMBER && args[2].type == Value::NUMBER && args[3].type == Value::NUMBER) + { + srand((unsigned int)args[3].num); + } + else + { + return Value(); + } + + Value v; + v.type = Value::VECTOR; + + for(int i=0; i<args[2].num; i++) + { + Value * r = new Value(frand(args[0].num,args[1].num)); + v.vec.append(r); + } + + return v; +} + + Value builtin_min(const Context *, const QVector<QString>&, const QVector<Value> &args) { if (args.size() >= 1 && args[0].type == Value::NUMBER) { @@ -300,6 +338,7 @@ void initialize_builtin_functions() { builtin_functions["abs"] = new BuiltinFunction(&builtin_abs); builtin_functions["sign"] = new BuiltinFunction(&builtin_sign); + builtin_functions["rands"] = new BuiltinFunction(&builtin_rands); builtin_functions["min"] = new BuiltinFunction(&builtin_min); builtin_functions["max"] = new BuiltinFunction(&builtin_max); builtin_functions["sin"] = new BuiltinFunction(&builtin_sin); |