Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.Pow(10,1.946) returns 0

Tags:

c#

xamarin

I am using the following code:

float test = (float)Math.Pow(10,1.946);

The problem is that this code returns 0 instead of 88.30799004. Also when using the following code, it will return 0:

double test = Math.Pow(10,1.946);

I am using Xamarin and I have set a breakpoint at the variable. With the exact same code it does go off, but returns 0, why is this?

like image 358
Jip Harthoorn Avatar asked Jan 30 '26 08:01

Jip Harthoorn


1 Answers

"Didn't use Debug.Write() and stepped over the breakpoint: it stayed 0. When I added Debug.Write() and stepped over the breakpoint, it did return the right value 88.30799004. That's kinda weird?"

Not as wierd as you think. One job of the "Just in Time" compiler or JiT is it to cut out dead code. While usually the routines are turned to "very little optimisation" during debug builds, some is still there. I once made this code to force the Runtime to run into the "2 GiB" limit. And nothing happened untill I actually added a output:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OOM_32_forced
{
    class Program
    {
        static void Main(string[] args)
        {
            //each short is 2 byte big, Int32.MaxValue is 2^31.
            //So this will require a bit above 2^32 byte, or 2 GiB
            short[] Array = new short[Int32.MaxValue];

            /*need to actually access that array
            Otherwise JIT compiler and optimisations will just skip
            the array definition and creation */
            foreach (short value in Array)
                Console.WriteLine(value);
        }
    }
}

Note that usually it is a quite nice and well working part. But with minimalistic test examples it is prone to cause such issues, unfortunately.

like image 181
Christopher Avatar answered Jan 31 '26 21:01

Christopher