OverflowException only in VB.net and not in C #

for self-education, I tried to find a way to create a height map myself. I searched googled a bit and found a function that creates pseudo random numbers.

    public static float Noise(int x)
    {
        x = (x << 13) ^ x;

        return (1f - ((x * (x * x * 15731 + 789221) + 1376312589) & 0x7FFFFFFF) / 1073741824.0f);
    }

Since the language of choice for me is VB.net, I translated this function into:

Private Function Noise(ByVal x As Integer) As Double
    x = (x << 13) Xor x

    Return (1.0R - ((x * (x * x * 15731.0R + 789221.0R) + 1376312589.0R) And &H7FFFFFFF) / 1073741824.0R)
End Function

If I use the C # version, I get results for x values ​​from 1 to 100. If I use the VB.net version, I get values ​​for x <6, but OverFlowExceptionfor x = 6. When I parse parts of this function, I found what's the crowded part

(x * x * 15731.0R)

So, my first question is: why am I getting OverFlowExceptionin VB.net, but not in C #? If the intermediate result is too large for its containing variable, it should be too large no matter which language I use.

: , VB.net?

.

+4
2

OverflowException VB.net, #?

VB , # - . #, , checked{ }:

public static float Noise(int x)
{
    x = (x << 13) ^ x;
    checked{
        return (1f - ((x * (x * x * 15731) + 1376312589) & 0x7FFFFFFF) / 1073741824.0f);
    }
}

, VB.net?

, "" #. , , , .

x double:

Private Function Noise(ByVal x As Integer) As Double
    x = (x << 13) Xor x

    Dim y As Double = x

    Return (1.0R - ((y * (y * y * 15731.0R) + 1376312589.0R) And &H7FFFFFFF) / 1073741824.0R)
End Function

" " VB, . VB , , #.

, , , , (And &H7FFFFFFF) . .

, . # float, VB Double. VB, #. , .

+10

. , OverFlowException VB.net , VB.net , # - .

- , VB.net, :

<StructLayout(LayoutKind.Explicit)>
Public Structure LongToIntegerNoOverflow
    <FieldOffset(0)>
    Public LongValue As Long
    <FieldOffset(0)>
    Public IntValue As Integer
End Structure

Noise

Private Function Noise(ByVal x As Integer) As Single
    Dim x1 As Long
    Dim x2 As LongToIntegerNoOverflow
    Dim x3 As LongToIntegerNoOverflow
    Dim x4 As Long

    x1 = (x << 13) Xor x

    x2.LongValue = x1 * x1 * 15731 + 789221
    x3.LongValue = x1 * x2.IntValue + 1376312589

    x4 = x3.IntValue And &H7FFFFFFF

    Return (1.0R - x4 / 1073741824.0R)
End Function

VB.net #.

0

All Articles