What did I do wrong with calculating percent in processing? - processing

I was writing a simple processing script that does an random boolean and counts how oft its 1 instead of 0.
then I added an counter of the total amount an random is done.
i wanted to use that for claculating the percentage of the 1ns.
anything works fine to this point.
then I wanted to do the calculating. it shows 0 no matter what i do.
the code goes like
bool r; //boolean for random
int t; //t fr true or 1
int f; //f for false or 0
int cnt; //cnt for total count
float p; //for the percentage
Void draw(){
r = int(random(2));
if (r==0){int(f++);}
if (r==1){int(t++);}
if (r<100){cnt++;}
p = t / cnt * 100; //calculating percentage.
text(p,10,100); //draws text on sceen at x=10 and y=100 but it always draws 0
}
Whats is wrong with that? What did I do wrong?

I think it is this problem: Why dividing two integers doesn't get a float?
So you can write something like that:
(t * 100.0f)/cnt

Related

C++ srand() repeating the same string of numbers [duplicate]

So, I'm trying to create a random vector (think geometry, not an expandable array), and every time I call my random vector function I get the same x value, though y and z are different.
int main () {
srand ( (unsigned)time(NULL));
Vector<double> a;
a.randvec();
cout << a << endl;
return 0;
}
using the function
//random Vector
template <class T>
void Vector<T>::randvec()
{
const int min=-10, max=10;
int randx, randy, randz;
const int bucket_size = RAND_MAX/(max-min);
do randx = (rand()/bucket_size)+min;
while (randx <= min && randx >= max);
x = randx;
do randy = (rand()/bucket_size)+min;
while (randy <= min && randy >= max);
y = randy;
do randz = (rand()/bucket_size)+min;
while (randz <= min && randz >= max);
z = randz;
}
For some reason, randx will consistently return 8, whereas the other numbers seem to be following the (pseudo) randomness perfectly. However, if I put the call to define, say, randy before randx, randy will always return 8.
Why is my first random number always 8? Am I seeding incorrectly?
The issue is that the random number generator is being seeded with a values that are very close together - each run of the program only changes the return value of time() by a small amount - maybe 1 second, maybe even none! The rather poor standard random number generator then uses these similar seed values to generate apparently identical initial random numbers. Basically, you need a better initial seed generator than time() and a better random number generator than rand().
The actual looping algorithm used is I think lifted from Accelerated C++ and is intended to produce a better spread of numbers over the required range than say using the mod operator would. But it can't compensate for always being (effectively) given the same seed.
I don't see any problem with your srand(), and when I tried running extremely similar code, I did not repeatedly get the same number with the first rand(). However, I did notice another possible issue.
do randx = (rand()/bucket_size)+min;
while (randx <= min && randx >= max);
This line probably does not do what you intended. As long as min < max (and it always should be), it's impossible for randx to be both less than or equal to min and greater than or equal to max. Plus, you don't need to loop at all. Instead, you can get a value in between min and max using:
randx = rand() % (max - min) + min;
I had the same problem exactly. I fixed it by moving the srand() call so it was only called once in my program (previously I had been seeding it at the top of a function call).
Don't really understand the technicalities - but it was problem solved.
Also to mention, you can even get rid of that strange bucket_size variable and use the following method to generate numbers from a to b inclusively:
srand ((unsigned)time(NULL));
const int a = -1;
const int b = 1;
int x = rand() % ((b - a) + 1) + a;
int y = rand() % ((b - a) + 1) + a;
int z = rand() % ((b - a) + 1) + a;
A simple quickfix is to call rand a few times after seeding.
int main ()
{
srand ( (unsigned)time(NULL));
rand(); rand(); rand();
Vector<double> a;
a.randvec();
cout << a << endl;
return 0;
}
Just to explain better, the first call to rand() in four sequential runs of a test program gave the following output:
27592
27595
27598
27602
Notice how similar they are? For example, if you divide rand() by 100, you will get the same number 3 times in a row. Now take a look at the second result of rand() in four sequential runs:
11520
22268
248
10997
This looks much better, doesn't it? I really don't see any reason for the downvotes.
Your implementation, through integer division, ignores the smallest 4-5 bit of the random number. Since your RNG is seeded with the system time, the first value you get out of it will change only (on average) every 20 seconds.
This should work:
randx = (min) + (int) ((max - min) * rand() / (RAND_MAX + 1.0));
where
rand() / (RAND_MAX + 1.0)
is a random double value in [0, 1) and the rest is just shifting it around.
Not directly related to the code in this question, but I had same issue with using
srand ((unsigned)time(NULL)) and still having same sequence of values being returned from following calls to rand().
It turned out that srand needs to called on each thread you are using it on separately. I had a loading thread that was generating random content (that wasn't random cuz of the seed issue). I had just using srand in the main thread and not the loading thread. So added another srand ((unsigned)time(NULL)) to start of loading thread fixed this issue.

How to generate random partitions of float number and each part has minimum value pMin?

for example:
I want to divide 33.38 into 5 parts, each part is equal or greater than 1.2:
2.71,3.3,18.7,1.56,7.11
function in pseudo code:
public static void printRandomPartition(float value,int numberOfParts,float pMin){
}
public static void main(String[] args){
//it will print 2.71,3.3,18.7,1.56,7.11
printRandomPartition(33.38,5,1.2);
}
another case:
divide 18.77 into 3 parts, each part is equal or greater than 3.2:
4.8,9.55,4.42
Of course the input and output may be ugly format float such as 3.82000000000003, it is just example only.
I searched some posts about it but seems most are about integers, and the method used in integers often uses array int myArray[n] (n is the integer to be divided), which is not useful to handle float. can anyone help?
pseudocode
function Divide(Sum, NParts, MinValue)
//subtract minimal values to deal with corrected sum
ASum = Sum - MinValue * NParts
//generate uniform randoms (in any reasonable range), take their sum
BSum = 0
for i = 0.. NParts - 1
Part[i] = Random
BSum = BSum + Part[i]
//scale randoms to get right corrected sum, then add minimal value to get initial sum
for i = 0.. NParts - 1
Part[i] = Part[i] * ASum / BSum + MinValue

Looking for an elegant way to get ±1-sequence in processing

I need an alternate sequence like 1, -1, 1, -1... asf. First I used if-statements for it, but it's dumb. Then I tried something like:
int n = 1;
...
do{
n = 0 + ( n * (-1));
} while(blabla)
It's ok, but I have to store n value from iteration to iteration. This isn't so pretty. How to compute that sequence from a control variable like frameCount?
Sorry, I am learning not only to code, but English too.
It's not very readable, but if you're looking for something purely "elegant," I suppose you could do something like:
int n = 1 - ((frameCount % 2) * 2);
If you're on an even frame you'll be subtracting (1 - 0), if you're on odd frame you'll be subtracting (1 - 2).
For readability, I recommend:
int n = (frameCount & 1) == 1 ? 1 : -1;
or
int n = -1;
if ((frameCount & 1) == 1) {
n = 1;
}
(Note that x & 1 extracts the lowest bit from x just like x % 2 does.)
Why don't you just do this
float n = 1 ;
void setup() {
....
}
void draw() {
....
n =-n;
....
}
I recently saw another fun way to create such a sequence using XOR magic.
int n = -1, t = 1 ^ -1;
...
do{
n ^= t;
}while(blabla);
Found in Algorithms for programmers, page 5.
One possibility is
((framecount & 1)<<1) -1;
On even frames, framecount & 1 will yield 0, and the result will then be -1. On odd frames, framecount & 1 will yield 1, and the result will be 1.
Or, less immediate but possibly much faster on some architectures,
frameCount-(frameCount^1)
When frameCount is odd, frameCount^1 will be equal to frameCount-1, and the result will then be 1. If frameCount is even, frameCount^1 will be equal to frameCount+1, giving -1.

How to compare int values?

I would like to know how to compare int values.
I would like to know that once I compare both 2 int values, I would like to know how far apart these 2 values are and if it is possible to put this in a 'if' statement.
The only problem I have is that (lets say int HELLO), HELLO's value always changes at random, so I would like to know how do I always compare HELLO's value and a different int's value on the go, so that at any moment if the result of both values are only 50 numbers off (negative or positive), it would trigger let's say timer2->Stop();.
Thank you.
If you have two int values, then you can subtract them to find out the difference between the two. Then in your if-test you just check if they are within 50 of each other and then execute the code...
Here's some pseudocode for you to work off of:
int valueOne = 100;
int valueTwo = 50;
int differenceBetweenValues = valueOne - valueTwo;
if ( (differenceBetweenValues >= 50) || (differenceBetweenValues >= -50) ) {
timer2->Stop();
}
You could then make that as a function and pass your values in (as you've stated they're different each time).
The distance between two int numbers is calculated as an absolute value of their difference:
int dist = abs(value1 - value2);
You can put it in an if statement or do anything you wish with the result:
if (abs(value1 - value2) > 50) ...

Adding the sum of numbers using a loop statement

I need serious help dividing the positive numbers and the negative numbers.
I am to accumulate the total of the negative values and separately accumulate the total of the positive values. After the loop, you are then to display the sum of the negative values and the sum of the positive values.
The data is suppose to look like this:
-2.3 -1.9 -1.5 -1.1 -0.7 -0.3 0.1 0.5 0.9 1.3 1.7 2.1 2.5 2.9
Sum of negative values: -7.8 Sum of positive
values: 12
So far I have this:
int main () {
int num, num2, num3, num4, num5, sum, count, sum1;
int tempVariable = 0;
int numCount = 100;
int newlineCount = 0, newlineCount1 = 0;
float numCount1 = -2.3;
while (numCount <= 150)
{
cout << numCount << " ";
numCount += 2;
newlineCount ++;
if(newlineCount == 6)
{
cout<< " " << endl;
newlineCount = 0;
}
}
**cout << "" << endl;
while (numCount1 <=2.9 )
{
cout << numCount1 << " ";
numCount1 += 0.4;
newlineCount1 ++;
} while ( newlineCount1 <= 0 && newlineCount >= -2.3 );
cout << "The sum is " << newlineCount1 << endl;**
return 0;
}
I do not know C/C++ but here is a general idea of the loop assuming the values are coming from an array. (since I am unaware of how they are coming in, i.e. user input, etc.)
Logic:
Use a for loop structure opposed to a while, to loop over each element of the array.
Initialize two variables to keep count, positiveSum and negativeSum.
At each iteration of the element, check to see if it's greater than 0. That's how you can divide the positive and negative numbers accordingly.
If greater than zero, add the element onto the running positiveSum, else add it to the running sum of negativeSum.
When the loop finishes, positiveSum and negativeSum should have the calculated sum.
If this is homework, (I don't remember if the homework tag was there prior to the question, or was added on later) this pseudo code should point you in the right direction without explicitly doing the entire work for you.
Pseudo Java Code (not tested or compiled)
// as a good convention, I always initialize variables,
// for numbers I always use zero's.
double positiveSum, negativeSum = 0.0;
// assuming array holds the array of values.
for (i=0; i < array.length; i++) {
// if positive, add it to the count
if (array[i] > 0) positiveSum = positiveSum + array[i];
// else negative
else negativeSum = negativeSum + array[i];
}
Once it's completed, both positiveSum and negativeSum should hold the correct calculated sum.
If you have any questions along the way, I can edit my answer to help you achieve the correct answer, I wish I could give it away but that's what your responsibilities are for homework.
I would loop through each number individually, let's call it currentValue
if the number is negative, negativeNumberTotal += currentValue
else if positive, positiveNumberTotal += currentValue
You will get your individual totals that way. Very simple.
You are clearly overcomplicating the problem. First of all you don't need two separate loops for the numbers, as there is a constant 0.4 difference between them, even between -0.3 and 0.1. You only have to check if it's negative or not to know how to sum them up.
Loops are simpler if you use an integer as counter. As you want 14 numbers you can simply count from 0 to 13, and from that you can easily calculate the corresponding floating point value.
Example C# code:
double negSum = 0.0, posSum = 0.0;
for (int i = 0; i < 14; i++) {
double number = -2.3 + (double)i * 0.4;
if (number < 0) {
negSum += number;
} else {
posSum += number;
}
}
You can of course use a floating point number in the loop, but then you need to take into account the inexact nature of floating point numbers. You should make sure to use an ending interval that is something like halfway between the last number that you want and the next.
double negSum = 0.0, posSum = 0.0;
for (double number = -2.3; number < 3.1; number += 0.4) {
if (number < 0) {
negSum += number;
} else {
posSum += number;
}
}
Also, when repeatedly accumulating floating point numbers (like adding 0.4 over and over again), you also accumulate rounding errors. Most numbers can't be represented exactly as floating point numbers, so it's likely that you are actually adding something like 0.3999999999999994225 instead of 0.4 each iteration. It's not likely to add up to something that is enough to show up in this small example, but you should be aware of this effect so that you can anticipate it in situations with more numbers.
You have several magic numbers, whose purpose I'm not sure of, e.g numcount1 = -2.3 In general you want to avoid magic numbers.
You might want to give your variables more descriptive names than num1, num2, etc.
Could you explain more precisely what the parameters are for your assignment?
EDIT:
I've noticed that you are using very weird conditions to control your loop. You are continuing until numcount1 is = 2.9, which is a very fragile sort of setup. The first thing I would do in your shoes is to rewrite your program so that the loop terminates when there are no more numbers to add. (Alternatively, you could just make it stop after, say 12 values.)
EDIT AGAIN:
OK, how about this
int sumOfPos = 0, sumOfNeg = 0, currentValue = -2.3, terminationValue = 2.9;
while (currentValue <= terminationValue) {
if ( /* there is a missing condition here */ ) {
// need a statement here to increment your negative counter
} else {
// need a statement here to increment your positive counter
}
}
// put some statements here to do output
This is easily solvable with pure math:
lowerBound = -2.3
upperBound = 2.9
incAmount = 0.4
signChange = lowerBound % incAmount
numBelowChange = -(lowerBound-signChange)/incAmount
avgNegValue = -(numBelowChange+1)/2.0*incAmount + signChange
sumOfNegative = numBelowChange*avgNegValue
numAboveChange = (upperBound-signChange)/incAmount
avgPosValue = (numAboveChange+1)/2.0*incAmount + signChange
sumOfPositive = numAboveChange*avgPosValue + signChange
It's more accurate, and more efficient than looping and adding.
With the constants you provided,
signChange = 0.1
numBelowChange = 6.0
avgNegValue = -1.3
sumOfNegative = -7.8
numAboveChange = 7.0
avgPosValue = 1.7
sumOfPositive = 12.0
If you're unfamiliar with the % operator, x%y means "divide x by y and return the remainder". So 5%2=1
http://en.wikipedia.org/wiki/Modulo_operator
I'm not a programmer, but I thought it was best to keep the inside of a loop as lean as possible. This version works without any if statements inside the loop, just simple addition. It's late at night, and I've had a couple of whiskies, but I think this algorithm would work (it worked when I tried implementing it in python). It's psuedo code, so you'll have to write it up in yr language of choice:
neg_total =0
abs_total=0
loop with i in all_your_numbers
total += i
abs_total += abs(i)
end
neg_total=(total-abs_total)/2
pos_total=abs_Total+neg_Total
print "sum of negative values =", neg_total
print "sum of positive values =", pos_total
I'm not sure if this is good programming practice, I'm just chuffed that it worked. Points if you can explain how.

Resources