概述
今天给大家介绍下Random的用法,想必大多数程序员对此用法都有所了解,今天之所以拾起这个话题,是因为在项目中发现一个问题,虽然random是随机采样的,但是他随机的效果并不是很理想,后来才了解到他是伪随机的,要想随机效果好还得控制好采样种子。那么怎么弄,下面就对此展开讲解.
开发环境:VS2019;
mvvm框架:Caliburn.Micro
源码
默认采样因子随机采样:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace ConsoleApp31
{
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
List<XyDTO> xyDTOs = new List<XyDTO>();
Random r = new Random();
for (int i = 0; i < 100; i++)
{
xyDTOs.Add(new XyDTO() { X = r.Next(-10,10),Y = r.Next(-10, 10)});
sb.AppendLine($"{xyDTOs[i].X},{xyDTOs[i].Y}");
}
WritelogFile(sb.ToString());
Console.WriteLine("success");
Console.ReadKey();
}
public static void WritelogFile(string content, string dataFullPath = null)
{
if(string.IsNullOrEmpty(dataFullPath))
{
dataFullPath = Directory.GetCurrentDirectory() + "\\DataFile.txt";
}
StreamWriter sw = new StreamWriter(dataFullPath, false);
sw.WriteLine(content);
sw.Close();
}
}
public class XyDTO
{
public double X { get; set; }
public double Y { get; set; }
}
}
采样效果如下:
更改采样种子后
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace ConsoleApp31
{
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
List<XyDTO> xyDTOs = new List<XyDTO>();
//Random r = new Random();
//for (int i = 0; i < 100; i++)
//{
// xyDTOs.Add(new XyDTO() { X = r.Next(-10,10),Y = r.Next(-10, 10)});
// sb.AppendLine($"{xyDTOs[i].X},{xyDTOs[i].Y}");
//}
byte[] buffer = Guid.NewGuid().ToByteArray();
int iSeed = BitConverter.ToInt32(buffer,0);
Random r = new Random(iSeed);
for (int i = 0; i < 100; i++)
{
xyDTOs.Add(new XyDTO() { X = r.Next(-10, 10), Y = r.Next(-10, 10) });
sb.AppendLine($"{xyDTOs[i].X},{xyDTOs[i].Y}");
}
WritelogFile(sb.ToString());
Console.WriteLine("success");
Console.ReadKey();
}
public static void WritelogFile(string content, string dataFullPath = null)
{
if(string.IsNullOrEmpty(dataFullPath))
{
dataFullPath = Directory.GetCurrentDirectory() + "\\DataFile.txt";
}
StreamWriter sw = new StreamWriter(dataFullPath, false);
sw.WriteLine(content);
sw.Close();
}
}
public class XyDTO
{
public double X { get; set; }
public double Y { get; set; }
}
}
采样效果图:
以上就是我对Random的介绍,希望能对大家有所帮助!
技术群:添加小编微信并备注进群
小编微信:mm1552923
公众号:dotNet编程大全