Mathf.ceil rounding 5 up to 6

Hi folks,

I have a simple script, part of which finds the cube root of a number, and then rounds it up to the next largest int.

It seems to mainly work fine, but it breaks down when the number that gets cube-rooted and then rounded up is 125!

The cube root generated is 5, but then doing a Mathf.ceil on this number raises the value to 6.

Can anyone give me any advice? Is it some kind of typing problem?

Thanks very much in advance for any help you can give me!

– Richard

using UnityEngine;
using System.Collections;

public class AsteroidCreator : MonoBehaviour {
	
	public GameObject asteroidComponentPrefab;
	public float componentSpacing = 0.2f;
	public int componentsSpawned;
	
	// Use this for initialization
	void Start ()
	{
		CreateAsteroid (125);
	}
	
	void CreateAsteroid (int asteroidSize)
	{
		print ("asteroidSize = " + asteroidSize);
		// edgeLength should be cube root of asteroidSize, rounded up to next largest integer
		float edgeLength = Mathf.Pow (asteroidSize, 1.0f / 3.0f);
		print ("edgeLength = " + edgeLength);
		edgeLength = Mathf.Ceil (edgeLength); // why doesn't this work for asteroidSize = 125??? Rounds 5.000000 up to 6...
		print ("edgeLength after Mathf.Ceil = " + edgeLength);
		
		float centerOffset = (componentSpacing * (edgeLength - 1) / 2);
		
		for (int i = 0; i < edgeLength; i++) {
			for (int j = 0; j < edgeLength; j++) {
				for (int k = 0; k < edgeLength; k++) {
					componentsSpawned++;
					if (componentsSpawned <= asteroidSize) {
						GameObject newComponent = Instantiate (asteroidComponentPrefab, new Vector3 ((i * componentSpacing) - centerOffset, (j * componentSpacing) - centerOffset, (k * componentSpacing) - centerOffset), Quaternion.identity) as GameObject;
						newComponent.transform.parent = this.transform;
					}
				}
			}
		}
	}
}

Ah yes, floating point… If you tested edgeLength > 5.0f in the case of asteroidSize = 125, it would be true. You could round it, or use .3333333f in Mathf.Pow instead of 1.0f/3.0f.

Ah, I see! Thank you very much, Eric5h5! I thought I’d checked for that, but apparently I didn’t check closely enough!

Your advice is very helpful - I fixed it by checking for a small range above 5 and rounding down.

This has been my first experience on Unity Answers, and it was a good one! Thank you!