Search Unity

Handling Massive numbers?

Discussion in 'Scripting' started by ackley14, Jul 6, 2015.

  1. ackley14

    ackley14

    Joined:
    Oct 31, 2014
    Posts:
    31
    Im looking for the best way to be able to handle massive numbers (i.e. 10^100) without unity being an idiot and returning "infinity"...
    i was able to contain 10^303 (1 centillion) in the editor but when i tried to create the number programatically via printing, it simply returned infinity..which is annoying since i need to be able to do very precise math with these numbers. i.e. removing 1 from 10^100 or whatever. and yes i'm using doubles. for some reason Math.pow's upper limit is only 38 despite a double's upper limit being E1^308...

    if mathf.pow doesn't work, would something else?
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,531
    Question...

    why?

    For what reason do you need 1 digit of precision when you're at 10^100? What would that even mean? You're talking a googol. It is estimated there is less than 10^80 atoms in the observable universe, based on the estimated mass of the observable universe if it were all just hydrogen (the smallest atom). You're saying you want a precision 10^20 greater than the precision of removing one atom from the observable universe.

    To what means would this be?



    As for a solution to what you want:
    https://bignumber.codeplex.com/

    But do note, numbers in the scale of 10^303 will be slow to operate on. Usually this sort of stuff is used for theoretical calculations where precision actually has some meaning, and the speed can be slow as things like framerate aren't a concern.
     
  3. landon912

    landon912

    Joined:
    Nov 8, 2011
    Posts:
    1,579
    Unity and .NET can handle large numbers, the problem is that the Inspector seems to be casting to a float for display only.

    On the topic of Mathf.Pow() not returning large enough values, it is because the math library works in floats and returns floats. You'll have to use your own double implementation or find one.

    Here:

    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3.  
    4. public class DoubleUpperLimit : MonoBehaviour
    5. {
    6.     public double largeNumber;
    7.  
    8.     public void Start ()
    9.     {
    10.         largeNumber = Double.MaxValue;
    11.  
    12.         Debug.Log (largeNumber);
    13.         Debug.Log (Double.MaxValue);
    14.         Debug.Log ("Is equal == " + (Math.Abs (largeNumber - Double.MaxValue) < 0.000001f));
    15.     }
    16. }
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    The reference was to Math.Pow. Mathf.Pow is just a wrapper for Math.Pow that casts to float instead of using doubles, and doubles are standard for .NET math functions. Note that doubles do not have the precision to do what this topic is discussing.

    --Eric