- Home /
I have no idea why this isnt working
i have made a script to try to find Pi, but the text component i have referenced just says 4, btw i am using this method "Leibniz formula for π" - https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80
Here is my code :
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class PaddleShape : MonoBehaviour {
private bool isNextNegative = false;
private int lastFraction = 1;
private decimal currentTotalOfFractions;
private Text text;
void Start()
{
text = GetComponent<Text>();
Invoke("Golden", 1.5f);
}
void Golden()
{
decimal fractionValue = 1 / lastFraction;
if (isNextNegative)
fractionValue = -fractionValue;
currentTotalOfFractions += fractionValue;
text.text = (currentTotalOfFractions * 4).ToString();
lastFraction += 2;
isNextNegative = !isNextNegative;
Invoke("Golden", Mathf.Epsilon);
}
}
Answer by NoseKills · Nov 11, 2017 at 10:22 AM
The part that looks suspicious here is
decimal fractionValue = 1 / lastFraction;
When you divide an integer by an integer, the result is always an integer.
If integer lastFraction
is greater than 1, the result is 0.
I didn't check the rest of the math but if you want to get a decimal result, make the "1" a "decimal 1" and the result will be 1 too.
Try
decimal fractionValue = 1m / lastFraction;
"m" is the suffix that makes an integer literal decimal.
Right, however i'm curious why he actually calculates PI manually with this infinite series and why he called the method Golden. The Leibniz formula for Pi converges extremely slow.
I also wouldn't recommend to use Invoke to call Golden itself this way. It's bad for performance. Using InvokeRepeating would make more sense here.