Random Number Selection Help

Hello All,
I have a question about the random number generator. I am trying to create a random process that will select between two numbers, which happen to be doubles, either 0.5 or -0.5. Yes, I want the random the calculation to either add .5 or subtract .5. So far I can only get the random number to add by .5 and never subtract by -.5. Help please!
class RandomTrialSets
public static void main (String[]args)
Random myRandom = new Random();
double randomOne = myRandom.nextDouble() * 0 + .5;
double randomTrials;
for (randomTrials = 5; randomTrials !=10; randomTrials += RandomOne)
System.out.println("it took this many times to complete the trial" + randomTrials);
Edited by: s_cheplick12 on Dec 14, 2009 8:19 PM

sabre150 wrote:
s_cheplick12 wrote:
I will try out both of your suggestions and write back in a little bit if they work. I want to the program to randomly ADD .5 or SUBTRACT .5 to each trial. So you want my second solution or Enceph's solution.
I thought it would look something like this (but this does not work):
double randomOne = myRandom.nextDouble(-.5 || .5)An interesting syntax!Sabre,
I tried out using your two suggestions, and they did not work the way I wanted. I'll try the boolean suggestion mentioned above, and write back how that worked out.
double randomOne = myRandom.nextDouble(-.5 || .5)
I actually think that if Java did have the power to read code that way it would be great. 

Similar Messages

  • Random NUMBER generator help..

    Hi all,
    i'm having issues with my random number generator i'm trying to fill my array with random numbers but i keep getting it filled with zeros.... can any one tell me what i'm doing wrong i can;t figure it out..
    for (int i =0; i < 100; i++){
                        int x=(int) (Math.random());
                        data[i] = x;
    }

    From the API "Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0."
    So casting the value to int is always going to result in a zero value.
    You need to multiply by a value that is one larger than the value you want to be your maximum. For example:
    int x = (int)(Math.random() * 100);
    should create a random number from 0 to 99

  • The salesperson for my iphone 4 said on Christmas morning we could go to our online account, select my number, select to change my SIM card, and enter the ICCID number so that I'd be able to use my iphone 4 today. I have not seen any such steps. Help?

    The salesperson for my iphone 4 said on Christmas morning we could go to our online account, select my number, select to change my SIM card, and enter the ICCID number so that I'd be able to use my iphone 4 today instead of my old phone (not an iphone). I have not seen any such steps. Help?

    I suspect the salesperson that told you that meant your online account with your carrier...have you tried logging into your carrier account online? To do this will require the sim number on your sim card, as well as the phone's IMEI number...you get the sim number off the sim card & the IMEI number, for the phone, is printed on the box.

  • Need help with a JavaScript to generate random number

    Hi
    First things first. I don't know the J of JavaScript.
    When I was thinking of some readymade solution to generate a random number in Captivate, I found this on a LinkedIn forum.
    1) Add a user variable to your project called "randomNumber". It's value can be zero.
    2) Add a Text Caption with "$$randomNumber$$" in it, to check whether your script is working.
    3) Add a button to the slide. Give it an On Success Action of Execute JavaScript. Turn off it's "Continue Playing the Project" checkbox.
    4) Add the following text in the button's Script_Window:
    var objCP = document.Captivate;
    var rand = 1 + Math.floor(Math.random() * 10);
    function onButtonClick(){
    objCP.cpEISetValue('randomNumber', rand);
    onButtonClick();
    However, this is (as the poster in the forum warned) not working for Captivate 7. Can somebody please help?
    I am open for any other methods of getting the same result.
    Thanks in advance,
    Sreekanth

    Hi Sreekanth,
    When testing, make sure you are testing from a web server where the web address begins with http or https.  When setting the captivate variable "randomNumber" try this instead:
    objCP.cpEISetValue('m_VarHandle.randomNumber', rand);
    That will only work for SWF output.  If you want it to work for both HTML5 and SWF output, try this code:
    window.onButtonClick = function(){
              var rand = generateRandomNumber(1, 10);
              setCpVariable('randomNumber', rand);
    window.generateRandomNumber = function(min, max){
              var randomNum = 0;
              if(!isNaN(parseFloat(min)) && !isNaN(parseFloat(max))){
                        min = Number(min);
                        max = Number(max);
                  randomNum = Math.floor(Math.random() * (max - min + 1)) + min;
              return randomNum;
    window.setCpVariable = function (cpUserVariableName, variableValue) {
              /* Check for HTML5 vs. SWF output */
              if (typeof window.cp === 'undefined') {
                        /* We have SWF output, so Get the Captivate Object */
                        var objCp = document.getElementById('Captivate');
                        if (objCp && objCp.cpEISetValue) {
                                  /* Set the Captivate User variable with the JavaScript variable, variableValue */
                                  objCp.cpEISetValue('m_VarHandle.' + cpUserVariableName, variableValue);
              } else {
                        /* We have HTML5 output */
                        /*If variable does not exist off of the window object, then use the variables manager*/
                        if (typeof window[cpUserVariableName] === 'undefined') {
                                  if (cp.vm && cp.vm.setVariableValue) {
                                            cp.vm.setVariableValue(cpUserVariableName, variableValue);
                        } else {
                                  window[cpUserVariableName] = variableValue;
    window.onButtonClick();
    Be sure to test this from a web server or else local security will prevent the javascript from executing.
    Best,
    Jim Leichliter

  • Random number in range generator plz help!

    hey hope someone can help me out, im sure its an easy one:
    var tstArray:Array = new Array(1,2,3);
    for (var a:uint=0; a<tstArray.length; a++)
    var x:Number = Math.floor((Math.random()*tstArray[a]));
    trace(x);
    tstArray.splice(a,1);
    i have this code but it doesnt do exectply what i want it to do. Im trying to generate a signle random number per click between 1 and 3 and when all numbers have been used up, remove this click listener.
    if u can help it'll be much appriciated
    thx pavel

    use:
    var fp1:farm_part1=new farm_part1();
    and any time you want to randomize an array use:
    var tstArray:Array = fp1.randomizeF([1,2,3]);
    package
    */import flash.utils.Timer;
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.*;
    import flash.media.Sound;
    import flash.events.TimerEvent;
    import flash.media.SoundChannel;
    import flash.media.SoundTransform;*/
    public class farm_Part1
    public function randomizeF(a:Array):Array
    {a.shuffle();
    return a;
    ///////////////////////////// change nothing below /////////////////////////////////////////
    function shuffle(a:Array)
    var p:int;
    var t:*;
    var ivar:int;
    for (ivar = a.length-1; ivar>=0; ivar--)
    p=Math.floor((ivar+1)*Math.random());
    t = a[ivar];
    a[ivar] = a[p];
    a[p] = t;
    }//randomAnimal
    }//class
    }//package

  • Help: JSP Random Number Generator

    hello every one,
    Im trying to generate a random number using currentTimeMillis(), in Jsp, can you help me out and advice me how can this be done please.

    First you say you want a random number, then you say you want a unique one. Which is it?
    Random numbers do not normally guaruntee uniqueness.
    is there away i could use the currentTimeMillis(), What would you use it for? System.currentTimeMillis() is commonly used as a seed for a random number generator. The java.util.Random class uses it like that - take a look at that API link.
    Or if its a homework question state the exact requirement - I'm guessing here.

  • Random (number) Help

    hi
    can anybody help me
    In the function random (number)
    if for eg. number=56
    then it generates any number between 0 and 56
    but if want to generate numbers between 56 and 567
    what should i do ?
    please help me

    function randomBetween(min:Number, max:Number):Number {
    var randomNum:Number =
    Math.round(Math.random()*(max-min)+min);
    return randomNum;
    randomBetween(156, 543) ;

  • I need help with random number in GUI

    hello
    i have home work about the random number with gui. and i hope that you can help me doin this application. and thank you very much
    Q1)
    Write an application that generates random numbers. The application consists of one JFrame,
    with two text fields (see the figures) and a button. When the user clicks on the button, the
    program should generate a random number between the minimum and the maximum numbers
    entered in the text fields. The font of the number should be in red, size 100, bold and italic.
    Moreover, if the user clicks on the generated number (or around it), the color of the background
    should be changed to another random color. The possible colors are red, green blue , black ,cyan
    and gray.
    Notes:
    �&#61472;The JFrame size is 40 by 200
    �&#61472;The text fields size is 10
    this is a sample how should the programe look like.
    http://img235.imageshack.us/img235/9680/outputgo3.jpg
    Message was edited by:
    jave_cool

    see java.util.Random

  • Help for random number generator???

    hi there can anyone how to make simple random number
    generator for slot machine , formula for chances in probability ,
    or simple random number generator for slot machine , thanks
    :)

    actualy the accurate RNG for slot machine ?? any idea?

  • How to Build a VI that generates a random number between 1 and 80 ....Help!!!!

    Build a VI that generates a random number between 1 and 80 
    Divides the random number by a number specified in the front panel.
    If the inputted number is zero, the VI program should turn on a LED in the front-panel to indicate a divide by zero error.
    Solved!
    Go to Solution.

    One quick question Edward, was the answer just in time for your monday morning class.
    Ton
    Free Code Capture Tool! Version 2.1.3 with comments, web-upload, back-save and snippets!
    Nederlandse LabVIEW user groep www.lvug.nl
    My LabVIEW Ideas
    LabVIEW, programming like it should be!

  • Random number generation that sticks

    Hello,
    I would appreciate any help with the appropriate JavaScript to generate a random 8 digit number XXXX-XXXX on a form when the user starts to enter data. This number would need to be permanent so that it can be used as a tracking identifier later.
    Thanks for looking.
    Dawson

    If you're using Oracle8i, you can use the new SAMPLE clause in the FROM clause of the SELECT statement to query a random sample from a single table. Otherwise, just write a simple random number generator in PL/SQL (see any good algorithm book under the topic "Psuedorandom number generator"). You need to understand a bit about statistics, if being "truly" random is important, to use these tools.

  • Random number generation with format 18XX88YYYYY

    I have been tryig to generate random numbers having
    format 18xx88yyyyy
    here
    18 followed by two random number then 88 followed by five random number. here 18 and 88 are fixed at location one,two,five and sixth position.
    but I am unable to get the logic .
    So please help
    Thanx
    Achyot

    After changing the column from number to varchar2 I am getting my correct result...
    create or replace function generateRandom return varchar2 is
    random varchar2(11);
    begin
    SELECT '18'|| lpad(ROUND (DBMS_RANDOM.VALUE (0, 100)),2,'0')|| '88'|| lpad(ROUND (DBMS_RANDOM.VALUE (0,
    100000)),5,'0')
    into random FROM DUAL;
    return random;
    end;
    create or replace procedure insertRandom is
    getNum varchar2(11);
    x number(3);
    cnt number;
    cursor checkpk is
    select random_no n from rand_no;
    begin
    cnt:=0;
    while (cnt<3054) loop
    x:=0;
    getNum:=generateRandom;
    for pkcheck in checkpk loop
    if getNum=pkcheck.n then
    x:=x+1;
    end if;
    end loop;
    if x=0 then
    insert into rand_no values(getNum);
    end if;
    select count(*) into cnt from rand_no;
    end loop;
    commit;
    end insertRandom;
    output:
    RANDOM_NO
    18388817929
    18658842315
    18028870847
    18898822037
    18678818255
    18248878003
    18558852407
    18878870907
    18998892135
    18538876212
    18908820740
    Thanx you everyone...

  • Does Labview have a Random Number Generator for U16 with a periodicity greater than 64 Million instances of U16words and one with SEED as the connector?

    We are doing some testing that requires 64MegaWords be written to our DSP memory  with random values to do a validity check and without repeating sequences with using the previous value as the seed for the next and us passing it the initial seed.  The dice one doesn't meet that criteria, and I was not sure how the continuous random number generator parameters work and if any of them would meet this criteria. Anyone have any information that might help?
    Thanks,
    Sue

    Hi suem,
    There is no reason why you couldn't simply write a pseudo-random number generator by yourself. Simply select a random number algorithm you want to use and implement it in LabVIEW. You do not need to interface code written in another language in order to implement a pseudorandom number generator. If you have a DAQ card or something, you can also use inputr noise or some other hardware soruce to generate real random numbers. For that also LabVIEW is an excellent tool.
    Tomi
    Tomi Maila

  • Why is that when I downloaded the iOS 7 for my iphone 5 that it changed my send and receive for imessages to a random number but my SMS messages are still linked to my phone number?

    Why is that when I downloaded the iOS 7 for my iphone 5 that it changed my send and receive for imessages to a random number but my SMS messages are still linked to my phone number?

    I just encountered this problem for the first time and stumbled upon this forum to find a solution.  I played around with it a bit and it seems that if you slide your finger from the bottom up, you will come upon that new screen that will allow you to do various functions with your phone (put it in airport mode, lock, etc.), you can select your Airport from this screen and play your music wirelessly from your phone; at least this was my experience. Hope this helps!

  • How do I assign images to grid cells based on their random number value?

    Hello everyone!
         I need a good point (or shove) in the correct direction.
    Background
         I've created (with previous help from this forum) a 12 x 9 random number grid which cycles through the numbers 1 to 9 a total of twelve times each. I've then created a button which shuffles the current grid's cells each time it is clicked. I now want to use 9 images that I have imported as individual symbols into the library (I have given them each their own class titled "skin1," "skin2," ... "skin9") as cell labels or the equivalent. I have also set the images up as individual movie clips (using the .Sprite class as the extended base class but keeping the actual image class names in line with their object name, i.e. the "skin1" image is the "skin1.as" class).
    Question
         How do I assign these images to the grid cells based on their respective values (ranging from 1 to 9) and have them populate the grid each time I click the "shuffle" button? So for example, in my grid the numbers 1 through 9 randomly appear 12 times each. Every time the number 4 appears in a cell, I want it to be assigned to the image "skin4" (which is just a graphic that looks like a button and has a fancy number "4" printed on it). Below is a chunk of the code I am using to draw the grid cells with:
    // Creates a grid cell when called by generateGrid().
    private funciton drawCell(_numeral:int):Sprite
              This is the code I am currently implementing to populate the grids with (although I
              don't want to use text labels as I want to fill each grid with an image according
              to its numerical value (1 to 9).
         var _label:TextField = new TextField();
         _label.multiline = _label.wordWrap = false;
         _label.autoSize = "center";
         _label.text = String(_numeral);
         // Add numerical label to cell array.
         cellLabels.push(_label);
         var _s:Sprite = new Sprite();
         _s.graphics.lineStyle(2, 0x019000);
         _s.graphics.drawRect(30, 0, cellW, CellH);
         _s.addChild(_label);
         return _s;
         While the following isn't working code, it will hopefully demonstrate what I want to achieve inside this function so I don't have to use the above snippet for text labels:
         //This will "hopefully" create an array of all 9 images by calling their classes.      var _imageArray:Array = [skin1, skin2, skin3, skin4, skin5 , skin6, skin7, skin8, skin9];      // This is what I want to happen for each cell using the above image array:      for (i = 0; i < cells; i++)      {           if (_numeral == 1)           {                // Insert skin1 image for each instance of #1 in the grid.           }           if (_numeral == 2)           {                // Insert skin2 image for each instance of #2 in the grid.           }           ...           if (_numeral == 9)           {                // Insert skin9 image for each instance of #9 in the grid.           }      } 
         Again, I don't want to use text labels. I have a custom skin graphic that I want to go over each number on the grid based on its numerical value (1 to 9). Any help with this is much appreciated!

    kglad,
         Thank you for your help with this one. Using the code below, I have successfully populated my grid cells with the desired corresponding graphics. I noticed one thing though regarding my use of the shuffle button with this particular implementation: even though the numerical values residing in each cell get shuffled, the original images remain in the grid rather than being replaced by new ones. The first code snippet below is the revised cell drawing function including your help; the second snippet shows you my simple shuffle button function (where the problem lies, I think).
    Snippet #1:
         // Creates a grid cell when called by generateGrid().
         private function drawCell(_numeral:int):Sprite
              var _label:TextField = new TextField();
              _label.multiline = _label.wordWrap = false;
              _label.autoSize = "center";
              // Creates a label that represents the numerical value of the cell.
              cellLabels.push(_label);
              var _s:Sprite = new Sprite();
              _s.graphics.lineStyle(2, 0x019000);
              _s.graphics.drawRect(30, 0, cellW, cellH);
              // Physically adds the labels to the grid.
              _s.addChild(_label);
              // Assigns a graphic class to a cell based on its numerical value.
              var _classRef:Class = Class(getDefinitionByName("skin" + _numeral));
              // Undefined variable for holding graphic classes.
              var _image:* = new _classRef();
              // Lines the images up with the grid cells.
              _image.x = 30;
              // Physically adds a graphic on top of a cell label.
              _s.addChild(_image);
              return _s;
         So far so good (although I question needing text labels at all if they are just going to remain invisible underneath the images, but enough about that for now). This next part is the reason that the images won't shuffle with the cell values, I think.
    Snippet #2:
         // When shuffleButton is clicked, this event shuffles
         // the number array and fills the cellLabels with the new values.
         private function onButtonShuffleClick(e:MouseEvent):void
              // Shuffles the number array.
              shuffle(numbers);
              // Verifies the array has been shuffled.
              trace("After shuffle:", numbers);
              // Loop replaces old cellLabels with new number array values.
              for (var i:int = 0; i < cells; i++)
                   cellLabels[i].text = String(numbers[i]);
         As you can see, it never replaces the original images that populate the grid. I tried using the _s.removeChild(image) function but that didn't work, nor would copying/pasting some of the code from snippet #1 directly into this function as it would cause another instance of the images to be placed over top of the existing ones rather than actually swapping them out. Any continued help here is greatly appreciated!
         PS Is there a quicker method for posting code into these forums without having to type it all out by hand again (i.e. copy/paste or drag/drop from my .fla or Notepad file directly into this thread)?

Maybe you are looking for

  • How to add portlets to the task flow page

    I am using WebCenter space and I want space users to be able to put the portlets into their group space pages. All the portlets are under portlet folder in the catalog. However, our requirement was to have a custom folders. For example, the user admi

  • Error while starting weblogic 5.1 sp11 using ANT script

    I am getting following error: But not sure why, If anyone has any clue please share with me. thanks [java] Unable to initialize server: weblogic.t3.srvr.T3Srvr$T3FatalInitializationException: weblogic.system.name (myserver) is not a directory [java]

  • Calling Custom XSLT java class from BPEL in SOA Suite 11g

    Hi All, Morning...need some help with this issue...we are currently on SOA Suite 11g (11.1.1.4) version. Earlier while we were on SOA Suite version 10g (10.1.3.3) we were calling the custom java classes from the xsl mapping for complex transformation

  • Latest version of UCCX Agent desktop in VDI or XenDesktop environment

    Is anyone out there using Agent Desktop for UCCX in a XenDesktop VDI environment. The release notes for the latest clients don't appear to list XenDesktop specifically but mentions VDI support and XenApp support.

  • Adobe 1998 Not in PS CC?

    I just got PS cc. I shoot in RAW.  I have an Epson R3000.  I have an iMac with Mavericks.  Adobe support just told me that "Adobe 1998" is no longer used in Printer Profiles and that it stopped with CS5.   Is this really true?  What profile should I