How to create a circular random variable without bias?
显示 更早的评论
I would like to create an uniformly random angle between 0 and 360 degree. My problem is that 0 is equivalent to 360, therefore 0 or 360 is more likely than any other angles, but how to correct this? I think this depends on the resolution of the rand function or the resolution of doubles? This is a small effect but I want to solve it precisely.
回答(1 个)
Image Analyst
2014-12-7
numberOfAngles = 1000; % Whatever you want
randomAngles = 360 * rand(1, numberOfAngles);
The chance that you'll ever get an angle that is exactly 0 or 360 is extraordinarily remote and not even anything you should worry about. If you want to limit yourself to integers, then you can use randi and just don't include 360
integerAngles = randi(360, 1, numberOfAngles) - 1;
3 个评论
The chance that rand replies exactly 0.0 or 1.0 is 2^-52 repsectively, so it is a fair estimation to call it "extraordinarily remote". But I've seen code, which fails when 1.0 is replied and it runs for many weeks "reliably", but fails randomly from time to time, of course. Such bugs are the programmers hell, so I do see a reason to care about such rare events.
David Young
2014-12-7
The documentation for rand() says it never returns exactly 0 or exactly 1. I guess that means that 360*rand will never evaluate to an exact 0 or 360. It's difficult to see why having these values missing from the distribution could matter, since so many other values are also missing.
John D'Errico
2014-12-7
编辑:John D'Errico
2014-12-7
As David points out, rand will NEVER return the endpoints, so the question is irrelevant. In fact, those values occur LESS often than others, since they never occur.
Sorry, but worrying about an event that happens (or not) with probability on the order of 2^-52 is a simple waste of time, IMHO. If a true zero DID happen, and it DID cause a crash in some circumstances, of course that is an issue to worry about. But worrying about whether that single event has probability 2^-52 or 2^-51 because you want to wrap the domain is just silly. If your random variable was a coarser thing, so the integers from 0-360, that would be a very different issue.
Think of it like this, with p = 2^-52, if you generate 1e6 random events per second, it would take on the order of 150 years before you would expect to see that one of those events. There are far better ways to spend your time than optimizing your code to worry about such an event.
类别
在 帮助中心 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!