Sold by Alltricks. Secure shopping. Real-Time Stock. Worldwide delivery.
Create a free Team Why Teams? Collectives on Stack Overflow. Learn more. Generate a random double between -1 and 1 Ask Question. Asked 6 years, 6 months ago. Modified 1 year, 7 months ago. Viewed 53k times. What I was trying to use was I also tried to seed srand with the time, but I think im doing something wrong there because it keeps throwing this error: "error: expected declaration specifiers or ' Iharob Al Asimi Eric Newman Eric Newman 1 1 gold badge 1 1 silver badge 11 11 bronze badges.
This means possible solutions are -1,0 and 1, no other double are possible. Look at c-random-float-number-generation — Lorenzo Belli. The answers provided so far mine included will not cover the full range of precision available in a double. How much precision do you need? I edited my answer to reflect the precision limitations. Please give more info on your requirements if you want something "better".
Add a comment. Sorted by: Reset to default. Highest score default Trending recent votes count more Date modified newest first Date created oldest first. Help us improve our answers. Are the answers below sorted in a way that puts the best answer at or near the top? Claire Nielsen 1, 1 1 gold badge 13 13 silver badges 29 29 bronze badges. Mehrshad Mehrshad 5 5 silver badges 21 21 bronze badges.
Lol at creative use of cosine. Every thousand calls or so, you will get a NaN. Not because of cos, although i believe cos infinity is also NaN, but you will very rarely get an infinity. What is related to cos is that the rng here will not be uniformly-distributed. The logic is simple and elegant: in the first call, first is -1, it is then compared to be less than zero, which updates it to true value 1.
The second call asks if first , now 1, is less than zero, which is false value 0 , so srand isn't called. Third is a charm, they say, so now first , which is 0, is asked if it is less than zero, which keeps being false for this and the next iterations. Next, you might need to guarantee that min-max is not zero, or else you will get a nasty division by zero or NAN.
For that we shall explicitly cause the correct error. Using errno. Just simplify your if with only two options: it is right, or it is not. Finally, I've preferred to work with float instead of double to not give too much trust on what this function can generate. To fill a float is reasonable, for all bits.
If you use double you will be mislead and overconfident in the capacity of this function. The last line, the return, is just a simple equation. I guess you can figure that out easily. I just like to explicitly cast to float so I can see the code's intention besides the compiler's interpretation.
DrBeco DrBeco I don't like this approach. Moving the seed into the generator function introduces a small runtime cost, and makes testing more difficult not repeatable. The way you expressed your first check is needlessly cryptic, IMO better to use a bool , and don't combine the assignment and check on one line.
OP did not specify a platform; getpid is not portable. Good catch about preventing division by 0, but I'm not a fan of putting errors in errno , especially in user code. The runtime cost is picayune. About the "criptic", I guess it was, yes. Actually, that is the nice part of the answer. Yep, getpid may need a portable similar if OP need it. But the idea is out there. Thanks for the zero-division cumpliment. And, well, errno is there to be used. All in all, thanks for your comment.
I hope this answer at least inspired your creativity. My best. Ensure your random number generator is properly seeded. Most of the rest simply arent worth the trouble. Should i set them to null in the end of the loop and later "garbage collect them"??
If you're storing almost million doubles in memory, yes that will tend to use up a lot of memory at at least 8 bytes a pop. There is garbage collection in C, but it's manual. You don't perform garbage collection on regular doubles. You are not creating two new doubles each iteration. You are re-using the same doubles that live on the stack.
The memory allocation happens before the loop, in some code you haven't shown here. After seeing that ,, iteration loop, I'm not sure we want to see the other code. I also don't want to know if he's stack-allocating ,,length double arrays. I know it could be very bad in term of design but i told u it's my first c program and i done it all by myself..
I'm surprised the program even compiles or runs, although I've never tried putting that much data in static storage so I don't really know. Maybe someone with better knowledge of C can provide some precisions. That being said, even using dynamic memory allocation isn't the way to go. Your basic problem here is that you try to generate all your points first, and then perform your statistical analysis on the whole bunch.
What you could do, and it would use almost no memory, is to only work with a single point at a time, i. This only ever uses the same two doubles, on the stack. Plus here it doesn't matter how many points you want, it'll take longer but it'll never use up any additional memory. Search In.
NET etc. Share More sharing options Followers 0. Posted March 4, Hello all, Im a newbie to C and I am not figuring out how to make a function that will generate a double between 0 and Link to comment Share on other sites More sharing options Recommended Posts. Veiva Posted March 4, ZakO Posted March 4, Argote Posted March 4,
Copy Code. Posted 1-Nov am Marian Spanik. Espen Harlinn 5-Nov pm. Good of you to point out that we now have a good api for random number generation as part of the standard library ;. Posted Oct pm Matt T Heffron. Thanks for the link. Well, you can do it very simply. Posted Oct pm WuRunZhe. WuRunZhe Oct pm. Could you accept my solution with blue button labeled "Accept Solution"? Hi, you can use this code: XML.
Posted Oct am fkassaie. Nice generalization. But why all the template stuff when you use double in the essential line? Posted 5-Nov am Hamed Moezzi Azimi. Posted 1-Nov pm Nasrin Abdollahzadeh. Posted 3-Nov pm rashin ghodratzade. Add your solution here. OK Paste as. Treat my content as plain text, not as HTML. Existing Members Sign in to your account. This email is in use. Do you need your password?
Submit your solution! When answering a question please: Read the question carefully. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome. Don't tell someone to read the manual.
Chances are they have and don't get it. Provide an answer or move on to the next question. This makes the point uniformly generated over all of the circle. I would like to thank archit91 for sharing this usefull information on LeetCode in this article. If accuracy is an issue here you can create random numbers with a finer graduation by randomizing the significant bits.
Let's assume we want to have a double between 0. In case of IEE double variables 53 significant bits and 53 bit randomization the smallest possible randomization gap for the 0 to problem will be. The downside is that 4 rand calls will be needed to obtain the randomized integral number assuming a 15 bit RNG. If the number of bits for the mantissa or the RNG is unknown the respective values need to be obtained within the function. Note: I don't know whether the number of bits for unsigned long long 64 bit is greater than the number of double mantissa bits 53 bit for IEE on all platforms or not.
Stack Overflow for Teams — Start collaborating and sharing organizational knowledge. Create a free Team Why Teams? Collectives on Stack Overflow. Learn more. Asked 12 years ago. Modified 7 months ago. Viewed k times. Improve this question. Radi Radi 6, 17 17 gold badges 58 58 silver badges 89 89 bronze badges. How to generate random doubles, and how to format doubles as strings, are completely separate issues. And come to think of it alternatively: generating evenly-distributed doubles and generating evenly-distributed decimals are somewhat different, although related, tasks.
Generating evenly-distributed integers is more closely related to the decimals problem. The paper starts with a short discussion of the historical shortcomings of the legacy rand and srand functions. Add a comment. Sorted by: Reset to default.
Highest score default Trending recent votes count more Date modified newest first Date created oldest first. Help us improve our answers. Are the answers below sorted in a way that puts the best answer at or near the top? Improve this answer. Note that the randomness of this can be limited. The range xxxxx,yyyyy suggests 10 decimal digits.
You should avoid rand if possible. It's been the only way to get random numbers for decades. ChamilaWijayarathna, You need to include cstdlib — Veridian. Show 3 more comments. Alessandro Jacopson Alessandro Jacopson You might want to update this with a more recent cppreference document, which is pretty good. Ryan Zurrin Ryan Zurrin 21 3 3 bronze badges. Galik Galik
The logic is simple and elegant: in the first call, first is -1, it is then compared to be less than zero, which updates it to true (value 1). The second call. freefloo.com › c-programming › random-double-nu. Hi Which function can I use to make random numbers in double. Normally the rand(), randomize and random is randomizing numbers in int.