Converting a float into a string fraction representation - java

In Java, I am trying to find a way to convert a float number into a fraction string. For example:
float num = 1.33333;
String numStr = Convert(num); // Should return "1 1/3"
float num2 = 1.333;
String numStr2 = Convert(num2); // Should also return "1 1/3"
float num3 = 0.5;
String numStr3 = Convert(num3); // Should return "1/2"
float num4 = 2.25;
String numStr4 = Convert(num4); // Should return "2 1/4"
Any ideas how to do this in Java?

The simplest approach might be to use trial and error.
public static String toFraction(double d, int factor) {
StringBuilder sb = new StringBuilder();
if (d < 0) {
sb.append('-');
d = -d;
}
long l = (long) d;
if (l != 0) sb.append(l);
d -= l;
double error = Math.abs(d);
int bestDenominator = 1;
for(int i=2;i<=factor;i++) {
double error2 = Math.abs(d - (double) Math.round(d * i) / i);
if (error2 < error) {
error = error2;
bestDenominator = i;
}
}
if (bestDenominator > 1)
sb.append(' ').append(Math.round(d * bestDenominator)).append('/') .append(bestDenominator);
return sb.toString();
}
public static void main(String... args) {
System.out.println(toFraction(1.3333, 1000));
System.out.println(toFraction(1.1428, 1000));
for(int i=1;i<100000000;i*=10) {
System.out.println("PI "+i+": "+toFraction(3.1415926535897932385, i));
}
}
prints
1 1/3
1 1/7
PI 1: 3
PI 10: 3 1/7
PI 100: 3 14/99
PI 1000: 3 16/113
PI 10000: 3 16/113
PI 100000: 3 14093/99532
PI 1000000: 3 140914/995207
PI 10000000: 3 244252/1725033

Look into chain fractions. This allows you to determine denominator and fraction within a given accuracy.
For Pi you can get 22/7 or 355/113 depending on when you choose to stop.

This might be of help:
http://www.merriampark.com/fractions.htm
Otherwise you'd need some way of telling Convert() how far out you want to take things. Maybe a maximum reduced demoninator or something like that. That way you'll get "1 1/3" for both of the first two examples you have above rather than "1 33333/100000" for the first and "1 333/1000" for the second.

Extract the fractional part of the number (for example, ((int) 0.5 + 1) - 0.5, then divide one by the result (1 / 0.5). You'll get the denominator of the fraction. Then cast the float to an int, and you'll get the integer part. Then concatenate both.
It's just a simple solution, and will work only if the numerator of the fraction is 1.
double n = 1.2f;
int denominator = 1 / (Math.abs(n - (int) n - 0.0001)); //- 0.0001 so the division doesn't get affected by the float point aproximated representation
int units = (int) n;
int numerator = units * denominator + 1;
System.out.println("" + numerator + "/" + denominator); //6/5
System.out.println("" + units + " 1/" + denominator); //1 1/5

Assume you have "0.1234567", then count how many numbers after the decimal point (which is 7). then multiply the number with 10 ^ 7, now you have "1234567".
divide 1234567 over 10 ^ 7. Then, simplify the fraction using the GCD of the two numbers.
0.1234567 * 10000000 = 1234567
=> 1234567 / 10000000
=> System.out.println(1234567 / gcd(1234567,10000000) + "/" + 10000000/gcd(1234567,10000000));

Modified the FOR loop to break the loop, when the best denominator is already identified.
if (error2 == 0) break;
public static String toFraction(double d, int factor) {
StringBuilder sb = new StringBuilder();
if (d < 0) {
sb.append('-');
d = -d;
}
long l = (long) d;
if (l != 0) sb.append(l);
d -= l;
double error = Math.abs(d);
int bestDenominator = 1;
for(int i=2;i<=factor;i++) {
double error2 = Math.abs(d - (double) Math.round(d * i) / i);
if (error2 < error) {
error = error2;
bestDenominator = i;
if (error2 == 0) break;
}
}
if (bestDenominator > 1)
sb.append(' ').append(Math.round(d * bestDenominator)).append('/') .append(bestDenominator);
return sb.toString();
}
public static void main(String... args) {
System.out.println(toFraction(1.3333, 1000));
System.out.println(toFraction(1.1428, 1000));
for(int i=1;i<100000000;i*=10) {
System.out.println("PI "+i+": "+toFraction(3.1415926535897932385, i));
}
}

Related

How to write a Taylor series as a function

I have to write a Taylor series until the 16th element that calculates sin and compare the values returned values with Math.sin. Well , everything works fine until the last time when instead of 0.00000 i get 0.006941.Where is my error and if somebody have an idea how to write this in a more professional way I would be very happy.
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
NumberFormat formatter = new DecimalFormat("#0.000000");
double val[] = {0, Math.PI / 3, Math.PI / 4, Math.PI / 6, Math.PI / 2, Math.PI};
for (int i = 0; i < val.length; i++) {
System.out.println("With Taylor method: " + formatter.format(Taylor(val[i])));
System.out.println("With Math.sin method: " + formatter.format(Math.sin(val[i])));
}
}
public static double Taylor ( double val){
ArrayList<Double> memory = new ArrayList<Double>();
double row = val;
for (int i = 0, s = 3; i < 16; i++, s = s + 2) {
double mth = Math.pow(val, s);
double result = mth / factorial(s);
memory.add(result);
}
for (int i = 0; i < 16; i++) {
if (i % 2 == 0) {
double d = memory.get(i);
row = row - d;
} else {
double d = memory.get(i);
row = row + d;
}
}
return row;
}
public static long factorial ( double n){
long fact = 1;
for (int i = 2; i <= n; i++) {
fact = fact * i;
}
return fact;
}
}
Your math is correct, but your factorials are overflowing once you get to calculating 21!. I printed out the factorials calculated.
factorial(3) = 6
factorial(5) = 120
factorial(7) = 5040
factorial(9) = 362880
factorial(11) = 39916800
factorial(13) = 6227020800
factorial(15) = 1307674368000
factorial(17) = 355687428096000
factorial(19) = 121645100408832000
factorial(21) = -4249290049419214848 // Overflow starting here!
factorial(23) = 8128291617894825984
factorial(25) = 7034535277573963776
factorial(27) = -5483646897237262336
factorial(29) = -7055958792655077376
factorial(31) = 4999213071378415616
factorial(33) = 3400198294675128320
It appears that your raising val to ever higher powers isn't significant enough to make a difference with the overflow until you get to the highest value in your array, Math.PI itself. There the error due to overflow is significant.
Instead, calculate each term using the last term as a starting point. If you have the last value you entered into memory, then just multiply val * val into that value and then divide the next two numbers in sequence for the factorial part.
That's because memory.get(i) is equal to memory.get(i - 1) * (val * val) / ((s - 1) * s). This also makes your calculation more efficient. It avoids the multiplication repetition when calculating the numerator (power part) and the denominator (the factorial calculation). This will also avoid the overflow which results from how you calculated the denominator separately.
My implementation of this idea substitutes this for the first for loop:
double mth = val;
for (int i = 0, s = 3; i < 16; i++, s = s + 2) {
mth = mth * val * val;
mth = mth / ((s - 1) * s);
memory.add(mth);
}
and places
double row = val;
between the for loops, to ensure that the first term is the initial sum as you had it before. Then you don't even need the factorial method.
This this I get 0.000000 for Math.PI.

Calculating PI with an special Algorithm

I have to calculate PI with this special algorithm for school:
pi = 4*(1/1 - 1/3 + 1/5 - 1/7 ... 1/n)
I've been trying a lot of things but it seems like I only get a never-ending loop because the condition for it is false, or my code is too complicated. The result I have to get is the calculated PI (only 6 decimals)=(the Algorithm for it).
Here's the code I've already tried:
public void PI()
{
double n=1.0;//while 3 counter
double z=1.0;//while 3 denominator
int i=0;//numerator for while 3
double pi=1.0;//Result
double x=0.0;//Calculated fractions
double y=1.0;//denominator for double x
double q=1; //Help for while 2
int f=0;//Help for while 3
while(new Double(Math.round(1000000.0*pi)).compareTo(new Double(Math.round(1000000.0*Math.PI)))==-1||new Double(Math.round(1000000.0*pi)).compareTo(new Double(Math.round(1000000.0*Math.PI)))==1) //while 1
{
while(new Double(Math.round(1000000.0*(4*x))).compareTo(new Double(Math.round(1000000.0*Math.PI)))==-1||new Double(Math.round(1000000.0*pi)).compareTo(new Double(Math.round(1000000.0*Math.PI)))==1)//while 2
{
if (q==1)
{
x+=0.1/y;
q++;
}
y+=2;
if(q==2)
{
x-=0.1/y;
q--;
}
y+=2;
i++;
}
pi=x*4.0;
}
while(f<=i)//while 3
{
System.out.println(n+"/"+z);
z+=2;
f++;
}
}
Your code looks overcomplicated. Try this:
/**
* Returns PI estimation based on equation:
* {#code PI' = 4*(1/1 - 1/3 + 1/5 - 1/7 ... 1/m)}
*
* #param n number of fractions in sum.
*/
public static double piEstimate(int n) {
double sum = 0;
for (int i = 0; i < n; i++) {
double fraction = (double) 1/(i*2+1);
int sign = (i % 2 == 0) ? 1 : -1;
sum += sign * fraction;
}
return 4*sum;
}
public static void main(String[] args) {
System.out.println("PI = " + piEstimate(10000));
}
you should add a System.out.println to see how the pi variable evolves in your second loop.

Computing Pi Using Leibniz Series what is delta(difference in running computation)?

I have to compute pi to six decimal precision using the leibniz series and I managed to do it except the assigment has some restrictions.
pi / 4 = 1 -1/3 + 1/5 - 1/7 ....
"
cannot utilize the math library π in your computation - direct or indirect. Use ONLY the delta (difference) of your running computation to determine when to stop your loop
"
I do not understand what this means by difference of your running computation. Another way I was told was "When your computed value ceases to change then your loop can stop"
package com.company;
public class Main {
public static void main(String[] args) {
double series = 0;
double denominator = 1;
double numerator = 1;
double pi;
double testingPi;
double formattedTestingPi = 0;
double formattedMathPi = Math.round(Math.PI * 1000000.0) / 1000000.0;
int max = 1200000;
int iterations = 0;
for(int i = 1; i < max;i++)
{
if((i % 2) != 0)
{
series = series + (numerator/denominator);
}
else if((i % 2) == 0)
{
series = series + ((numerator/denominator) * -1);
}
denominator = denominator + 2;
testingPi = series * 4;
formattedTestingPi = (Math.round(testingPi * 1000000.0))/1000000.0;
if( formattedTestingPi == formattedMathPi)
{
iterations = i;
i = max;
System.out.println("We stop");
}
}
pi = series * 4;
System.out.println("Number of Iterations :" + iterations);
System.out.println("Unformatted Series :" + series);
System.out.println("Unformatted Math Library PI:" + Math.PI);
System.out.println("Unformatted Computed PI:" + pi);
System.out.println("Formatted Computed PI:" + formattedTestingPi);
System.out.println("Formatted Math Library PI:" + formattedMathPi);
}
}
I do not want the solution to the assignment, I just want to know
what does delta of computation mean and how is it different what I'm doing right now?
Output
Number of Iterations :1181461
Unformatted Series :0.7853983749998679
Unformatted Math Library PI:3.141592653589793
Unformatted Computed PI:3.1415934999994715
Formatted Computed PI:3.141593
Formatted Math Library PI:3.141593

Fraction to Recurring Decimal

Working on this problem, and also did a few reference to similar solutions. One thing I am confuse is, why we break the loop as long as there is one repetitive number? Is it possible the number repeat for 2-3 times and then changed to another different number? Thanks.
I mean this part specifically,
if (map.containsKey(num)) {
int index = map.get(num);
res.insert(index, "(");
res.append(")");
break;
}
The problem,
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".
Given numerator = 2, denominator = 3, return "0.(6)".
public class Solution {
public String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) {
return "0";
}
StringBuilder res = new StringBuilder();
// "+" or "-"
res.append(((numerator > 0) ^ (denominator > 0)) ? "-" : "");
long num = Math.abs((long)numerator);
long den = Math.abs((long)denominator);
// integral part
res.append(num / den);
num %= den;
if (num == 0) {
return res.toString();
}
// fractional part
res.append(".");
HashMap<Long, Integer> map = new HashMap<Long, Integer>();
map.put(num, res.length());
while (num != 0) {
num *= 10;
res.append(num / den);
num %= den;
if (map.containsKey(num)) {
int index = map.get(num);
res.insert(index, "(");
res.append(")");
break;
}
else {
map.put(num, res.length());
}
}
return res.toString();
}
}
thanks in advance,
Lin
The code doesn't stop when it sees a digit repeated. It stops when it notes that it has reached a state which it was already in. If it reaches the same state again, it means that we are about to repeat a division that we have already done, which means that the dividend and remainder are going to be the same, and we are going to do the same series of steps we have already done.
When that happens, it means a repetition, and it stops and adds the parentheses.
For example, let's divide 123 by 999. This should give us the repeating decimal 0.123123123..., so the output should be 0.(123).
123 / 999 is 0. The remainder is 123. We start with 0.
Multiply the remainder by 10. Now we have 1230 / 999. Dividend is 1, remainder is 231. Now we have 0.1
Multiply the remainder by 10. Now we have 2310 / 999. Dividend is 2, remainder is 312. Now we have 0.12
Multiply the remainder by 10. Now we have 3120 / 999. Dividend is 3, remainder is 123. Now we have 0.123
Multiply the remainder by 10. Now we have 1230 / 999... wait, we have already done that! That means that as we continue to divide, we'll get to that number again and again. Stop and put parentheses around the repeating part.
The map is there to tell us which numbers we have already divided, and at which index in the StringBuilder. When we find a number we have already divided, we use that index to know where to insert the parenthesis.
Clearly it's possible to have a decimal number with two or more decimals recurring and then a different decimal. For example 449/1000 = 0.449
Here is my solution in Java to this problem:
/**
* Given two integers a and b, return the result as a String.
* Display the repeating part of the fraction in parenthesis.
*
* Runs in O(b)
*
* #author Raed Shomali
*/
public class Divider {
private static final String DOT = ".";
private static final String ERROR = "ERROR";
private static final String LEFT_PARENTHESIS = "(";
private static final String RIGHT_PARENTHESIS = ")";
public static String divide(final int a, final int b){
if (b == 0) {
return ERROR;
}
int value = a / b;
int remainder = a % b;
return String.valueOf(value) + DOT + divider(remainder, b);
}
private static String divider(final int a, final int b) {
final Map<Integer, Integer> remainderIndexMap = new HashMap<>();
final List<Integer> values = new ArrayList<>();
int value;
int remainder = a;
while (!remainderIndexMap.containsKey(remainder)) {
remainderIndexMap.put(remainder, values.size());
remainder *= 10;
value = remainder / b;
remainder = remainder % b;
values.add(value);
}
final int index = remainderIndexMap.get(remainder);
final StringBuilder result = new StringBuilder();
for (int i = 0; i < index; i++) {
result.append(values.get(i));
}
result.append(LEFT_PARENTHESIS);
for (int i = index; i < values.size(); i++) {
result.append(values.get(i));
}
result.append(RIGHT_PARENTHESIS);
return result.toString();
}
}
Basically, the idea is simple. Using the same long division technique, you know when to stop when you have already seen the same remainder value.
Here are some test cases to show a few different scenarios:
divide(0, 0) // "ERROR"
divide(1, 2) // "0.5(0)"
divide(0, 3) // "0.(0)"
divide(10, 3) // "3.(3)"
divide(22, 7) // "3.(142857)"
divide(100, 145) // "0.(6896551724137931034482758620)"
If you are interested in a solution written in Go, you can find it here https://github.com/shomali11/util
This problem is actually very simple to solve if we use the long division technique that we learnt in 4th grade.
Suppose you need to divide 92 by 22. How do you do it using the long division method. How do you detect a repeating pattern?
Simple, you know you have a repeating pattern of decimals when you encounter a previously encountered reminder. You'll need to store the reminders and the corresponding index of the result in a dictionary and using the same you could detect/print repeating decimals. Working python code below.
def divide(numerator, denominator):
sign, res, lead = '', '', ''
if (numerator < 0) ^ (denominator < 0) and numerator != 0:
sign = '-'
numerator = abs(numerator)
denominator = abs(denominator)
remainders = defaultdict(list)
if numerator < denominator:
lead = '0'
_x = str(numerator)
r = 0
i = 0
j = 0
while True:
if i < len(_x):
d = int(str(r)+_x[i])
q = d // denominator
if not (q == 0 and len(res) == 0):
res += str(q)
r = d - (q * denominator)
i += 1
elif i >= len(_x) and j <= 9223372036854775807:
if r == 0:
return sign+lead+res
if j == 0:
remainders[r] = [True, len(res)+1]
res += '.'
d = int(str(r) + '0')
q = d // denominator
res += str(q)
r = d - (q * denominator)
if remainders[r] and remainders[r][0]:
res = res[0:remainders[r][1]] + '(' + res[remainders[r][1]:] + ')'
return sign+lead+res
remainders[r] = [True, len(res)]
j += 1
else:
return sign+lead+res

Java - Odd error message when converting double to BigDecimal

In a program, a double is being converted to BigDecimal. This returns a very strange error message.
public static double riemannFuncForm(double s) {
double term = Math.pow(2, s)*Math.pow(Math.PI, s-1)*
(Math.sin((Math.PI*s)/2))*gamma(1-s);
if(s == 1.0 || (s <= -1 && s % 2 == 0) )
return 0;
else if (s >= 0 && s < 2)
return getSimpsonSum(s);
else if (s > -1 && s < 0)
return term*getSimpsonSum(1-s);
else
return term*standardZeta(1-s);
}
BigDecimal val = BigDecimal.valueOf(riemannFuncForm(s));
System.out.println("Value for the Zeta Function = "
+ val.toEngineeringString());
This returns
Exception in thread "main" java.lang.NumberFormatException
What is causing this error message? Does BigDecimal.valueOf(double) not work correctly since this is referenced through another method?
Full program
/**************************************************************************
**
** Euler-Riemann Zeta Function
**
**************************************************************************
** XXXXXXXXXX
** 06/20/2015
**
** This program computes the value for Zeta(s) using the standard form
** of Zeta(s), the Riemann functional equation, and the Cauchy-Schlomilch
** transformation. A recursive method named riemannFuncForm has been created
** to handle computations of Zeta(s) for s < 2. Simpson's method is
** used to approximate the definite integral calculated by the
** Cauchy-Schlomilch transformation.
**************************************************************************/
import java.util.Scanner;
import java.math.*;
public class ZetaMain {
// Main method
public static void main(String[] args) {
ZetaMain();
}
// Asks the user to input a value for s.
public static void ZetaMain() {
double s = 0;
double start, stop, totalTime;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the value of s inside the Riemann Zeta " +
"Function: ");
try {
s = scan.nextDouble();
}
catch (Exception e) {
System.out.println("You must enter a positive integer greater " +
"than 1.");
}
start = System.currentTimeMillis();
if (s == 1)
System.out.println("The zeta function is undefined for Re(s) " +
"= 1.");
else if (s < 2) {
BigDecimal val = BigDecimal.valueOf(riemannFuncForm(s));
System.out.println("Value for the Zeta Function = "
+ val.toEngineeringString());
}
else
System.out.println("Value for the Zeta Function = "
+ BigDecimal.valueOf(getStandardSum(s)).toString());
stop = System.currentTimeMillis();
totalTime = (double) (stop-start) / 1000.0;
System.out.println("Total time taken is " + totalTime + " seconds.");
}
// Standard form of the Zeta function.
public static double standardZeta(double s) {
int n = 1;
double currentSum = 0;
double relativeError = 1;
double error = 0.000001;
double remainder;
while (relativeError > error) {
currentSum = Math.pow(n, -s) + currentSum;
remainder = 1 / ((s-1)* Math.pow(n, (s-1)));
relativeError = remainder / currentSum;
n++;
}
System.out.println("The number of terms summed was " + n + ".");
return currentSum;
}
// Returns the value calculated by the Standard form of the Zeta function.
public static double getStandardSum(double s){
return standardZeta(s);
}
// Approximation of the Gamma function through the Lanczos Approximation.
public static double gamma(double s){
double[] p = {0.99999999999980993, 676.5203681218851,
-1259.1392167224028, 771.32342877765313,
-176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6,
1.5056327351493116e-7};
int g = 7;
// Implements Euler's Reflection Formula.
if(s < 0.5) return Math.PI / (Math.sin(Math.PI * s)
*gamma(1-s));
s -= 1;
double a = p[0];
double t = s + g + 0.5;
for(int i = 1; i < p.length; i++){
a += p[i] / (s+i);
}
return Math.sqrt(2*Math.PI)*Math.pow(t, s+0.5)
*Math.exp(-t)*a;
}
/* Riemann's Functional Equation - Directly calculates the value of
Zeta(s) for s < 2.
1. The first if statement handles the case when s < 0 and s is a
multiple of 2k. These are trivial zeroes where Zeta(s) is 0.
2. The second if statement handles the values of 0 < s < 2. Simpson's
method is used to numerically compute an approximation of the
definite integral.
3. The third if statement handles the values of -1 < s < 0. Recursion
is used alongside an approximation through Simpson's method.
4. The last if statement handles the case for s <= -1 and is not a
trivial zero. Recursion is used directly against the standard form
of Zeta(s).
*/
public static double riemannFuncForm(double s) {
double term = Math.pow(2, s)*Math.pow(Math.PI, s-1)*
(Math.sin((Math.PI*s)/2))*gamma(1-s);
if(s == 1.0 || (s <= -1 && s % 2 == 0) )
return 0;
else if (s >= 0 && s < 2)
return getSimpsonSum(s);
else if (s > -1 && s < 0)
return term*getSimpsonSum(1-s);
else
return term*standardZeta(1-s);
}
// Returns the function referenced inside the right hand side of the
// Cauchy-Schlomilch transformation for Zeta(s).
public static double function(double x, double s) {
double sech = 1 / Math.cosh(x); // Hyperbolic cosecant
double squared = Math.pow(sech, 2);
return ((Math.pow(x, s)) * squared);
}
// Simpson's rule - Approximates the definite integral of f from a to b.
public static double SimpsonsRule(double a, double b, double s, int n) {
double simpson, dx, x, sum4x, sum2x;
dx = (b-a) / n;
sum4x = 0.0;
sum2x = 0.0;
// 4/3 terms
for (int i = 1; i < n; i += 2) {
x = a + i * dx;
sum4x += function(x,s);
}
// 2/3 terms
for (int i = 2; i < n-1; i += 2) {
x = a + i * dx;
sum2x += function(x,s);
}
// Compute the integral approximation.
simpson = function(a,s) + function(a,b);
simpson = (dx / 3)*(simpson + 4 * sum4x + 2 * sum2x);
return simpson;
}
// Handles the error for for f(x) = t^s * sech(t)^2. The integration is
// done from 0 to 100.
// Stop Simspson's Method when the relative error is less than 1 * 10^-6
public static double SimpsonError(double a, double b, double s, int n)
{
double futureVal;
double absError = 1.0;
double finalValueOfN;
double numberOfIterations = 0.0;
double currentVal = SimpsonsRule(a,b,s,n);
while (absError / currentVal > 0.000001) {
n = 2*n;
futureVal = SimpsonsRule(a,b,s,n);
absError = Math.abs(futureVal - currentVal) / 15;
currentVal = futureVal;
}
// Find the number of iterations. N starts at 8 and doubles
// every iteration.
finalValueOfN = n / 8;
while (finalValueOfN % 2 == 0) {
finalValueOfN = finalValueOfN / 2;
numberOfIterations++;
}
System.out.println("The number of iterations is "
+ numberOfIterations + ".");
return currentVal;
}
// Returns an approximate sum of Zeta(s) through Simpson's rule.
public static double getSimpsonSum(double s) {
double constant = Math.pow(2, (2*s)-1) / (((Math.pow(2, s)) -2)*
(gamma(1+s)));
System.out.println("Did Simpson's Method.");
return constant*SimpsonError(0, 100, s, 8);
}
}
Would I have to change all of my double calculations to BigDecimal calculations in order to fix this?
Nope. All you would need to do is to catch and handle the NumberFormatException appropriately. Or, test for NaN and Inf before attempting to convert the double.
In this case, you are only using BigDecimal for formatting in "engineering" syntax. So another alternative would be to do the formatting directly. (Though I haven't found a simple way to do that yet.)
This error occurs with you because BigDecimal.valueOf(value) does not accept "NaN" "Not a Number" as parameter and the following expression will return NaN
Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s)
this Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2)) will evaluate -0.0
and this function gamma(1-s) will evaluate "Infinity"
So -0.0 * Infinity equal NaN in java
please see this to know When can Java produce a NaN.
When can Java produce a NaN?

Categories

Resources