如何初始化一个特定的时间间隔在C#中分隔的数字数组 [英] How to initialize an array with numbers separated by a specific interval in C#

查看:503
本文介绍了如何初始化一个特定的时间间隔在C#中分隔的数字数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

欲创建包含的值从0到1以0.1间隔的阵列。我可以使用:

I want to create an array containing values from 0 to 1 with interval of 0.1. I can use:

float[] myArray = new float[10];
float increment = 0.1;
for(i = 0; i < 10; i++)
{
   myArray[i] = increment;
   increment += 0.1;
}

我想知道是否有像 Enumerable.Range 一个功能,允许同时指定区间增量。

I was wondering whether there is a function like Enumerable.Range that permits to specify also the increment interval.

推荐答案

一个有趣的事实是,迄今为止发布的每一个答案都有的固定的bug 的对你提出的code,但只有一个人叫出来,他们已经这样做了。

An interesting fact is that every answer posted so far has fixed the bug in your proposed code, but only one has called out that they've done so.

二进制浮点数字与不是两个精确的功率的一部分的任何数量打交道时具有的再presentation误差的。 (3.0 / 4.0是一个重新presentable馏分因为底部是二的幂;1.0 / 10.0是不是)

Binary floating point numbers have representation error when dealing with any quantity that is not a fraction of an exact power of two. ("3.0/4.0" is a representable fraction because the bottom is a power of two; "1.0/10.0" is not.)

因此​​,当你说:

for(i = 0; i < 10; i++) 
{
    myArray[i] = increment;    
    increment += 0.1; 
} 

您实际上并不是由1.0 / 10.0递增的增量。你是一个具有两个的底部精确的功率的最近重新presentable分数递增它。所以其实这相当于:

You are not actually incrementing "increment" by 1.0/10.0. You are incrementing it by the closest representable fraction that has an exact power of two on the bottom. So in fact this is equivalent to:

for(i = 0; i < 10; i++) 
{
    myArray[i] = increment;    
    increment += (exactly_one_tenth + small_representation_error);
} 

那么,什么是第十值的增加​​?显然,这是 10 *(exactly_one_tenth + small_re presentation_error)这显然等于 exactly_one + 10 * small_re presentation_error 您已经十乘以再presentation误差的大小。

So, what is the value of the tenth increment? Clearly it is 10 * (exactly_one_tenth + small_representation_error) which is obviously equal to exactly_one + 10 * small_representation_error. You have multiplied the size of the representation error by ten.

任何时候你多次加在一起的两个浮点数,以后每次除了增加总量略有总重presentation错误,并且增加了,从字面上看,一个潜在的大错误。在某些情况下,你正在总结少数十万或上百万的误差可能会变得的远远大于实际总较大的。

Any time you repeatedly add together two floating point numbers, each subsequent addition increases the total representation error of the sum slightly and that adds up, literally, to a potentially large error. In some cases where you are summing thousands or millions of small numbers the error can become far larger than the actual total.

远更好的解决办法就是做别人都做了。 从整数重新计算分数,每次即可。这样的每个结​​果的都有自己的小重presentation错误;它不累积previously计算结果的再presentation错误。

The far better solution is to do what everyone else has done. Recompute the fraction from integers every time. That way each result gets its own small representation error; it does not accumulate the representation errors of previously computed results.

这篇关于如何初始化一个特定的时间间隔在C#中分隔的数字数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆