Double function not returning Double value? - java

public class Nitin12assignA6 {
public static void main(String args[]) throws IOException {
series ob = new series();
ob.input();
ob.findSum();
ob.display();
}
}
class series {
int x, n;
double sum;
series() {
x = n = 0;
sum = 0.0f;
}
void input() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter the value of x = ");
x = Integer.parseInt(in.readLine());
System.out.print("Enter the value of n = ");
n = Integer.parseInt(in.readLine());
}
void display() {
System.out.println("The sum of Series upto " + n + " terms is: " + sum);
System.out.println();
}
long fact(int num) {
if(num == 1) {
return 1;
}
return num * fact(num - 1);
}
int power(int num, int exp) {
if(exp == 1) {
return 1;
}
return num * power(num, exp - 1);
}
double term(int numr, long denom) {
return(numr / denom);
}
void findSum() {
int u = 2, l = 4;
sum = 1.0f;
for(int i = 0; i < n; i++) {
if(l % 8 == 0) {
sum += term(power(x, u), fact(l));
// Test start
System.out.println("add" + sum + " power " + power(x, u) + " fact " + fact(l) + " x " + x + " u " + u
+ " l " + l);
System.out.println("term " + term(power(x, u), fact(l)));
System.out.println("test term " + term(5, 2)); // printing 2.0
// instead of 2.5
// Test end
} else {
sum -= term(power(x, u), fact(l));
// Test start
System.out.println("minus" + sum + " power " + power(x, u) + " fact " + fact(l) + " x " + x + " u " + u
+ " l " + l);
System.out.println("term " + term(power(x, u), fact(l)));
// Test end
}
u += 2;
l += 4;
}
}
}
//double term(int numr,long denom)
//{return (numr/denom);}
This function is not returning double value. Please help... This program is find a sum a series upto n terms. Example - test term is returning 2.0 instead of 2.5... Thanks.

You need to cast explicitly to double before devision.
double term(int numr, long denom) {
return ((double)numr / denom);
}

The casting to double is done on the value resulting from the division, so you can read
double term(int numr,long denom) {
return (double) (numr/denom);
}
So numr/denom is evaluated first, and since int/long type is long, the result would be 2L. Then it is casted to double. If you want it to be evaluated a double, do
double term(int numr,long denom) {
return ((double)numr/denom);
}

try
double term(int numr, long denom) {
return ((double) numr/denom);
}
your version had int/long which will always return a non floating point number.
See this:
int a = 2;
int b = 4;
double c = a/b; // 0.0
double d = ((double) a/b); // 0.5

double term(int numr, long denom) {
return (numr / denom);
}
The return value is double but the devision (numr / denom) creates a long which then is converted to double.

This may help.
double term(int numr, long denom) {
return ((double)numr / denom);
}

Related

Math in Java(Combinatorics)

My problem is:
My math formula is:
In this case X = N; Y = L;U = K;
public class Play {
public static void main(String args[]) {
//n!(n−k−1)!
int n = 10;
int k =2;
int l = 12;
long result;
result = (calculaFator(n) / calculaFator(n-k-1));
result= (long) (result * Math.pow((n-k),(l-k)-1));
System.out.println(result);
}
public static long calculaFator(long x) {
long f = x;
while (x > 1) {
f = f * (x - 1);
x--;
}
return f;
}
}
It should be 721599986, but it is giving me 96636764160
I have some samples:
With n=10, k=2, l=12 it should be 721599986
With n=10, k=2, l=16 it should be 626284798
With n=10, k=1, l=20 it should be 674941304
With n=5, k=2, l=8 it should be 10800
The java codes is working according to your stated formula.
It seems like the formula is wrong rather than the codes. (or expected results or your x,u,y mapping to n,l,k is incorrect?)
int x = 10;
int u = 2;
int y = 12;
long numerator = calculaFator(x);
long denominator = calculaFator(x - u - 1);
int xu1 = x - u - 1;
long result = numerator / denominator;
System.out.println();
System.out.println(x + "!= numerator: " + numerator); //10!= numerator: 3_628_800
System.out.println(xu1 + "!= denominator: " + denominator); //7!= denominator: 5_040
System.out.println("result1: " + result); //result1: 720 (correct)
int xu = x - u;
int yu1 = y - u - 1;
double remainderPlaylist = Math.pow(xu, yu1);
System.out.println(xu + "^" + yu1 + " = " + remainderPlaylist);//8^9 = 1.34217728E8
System.out.println(xu + "^" + yu1 + " = " + (long) remainderPlaylist);//8^9 = 134_217_728 (correct)
long mul = (long) (result * remainderPlaylist);
System.out.println(result + "x" + (long)remainderPlaylist + " = " + mul); //720x134_217_728 = 96_636_764_160 (mathematically correct)

Implementing comparable interface to rational class(java)

I am a beginner in Java and this is my first time using Comparable interface. I don't understand why it keeps returning zero when comparing r1 and r2. Can someone explain to me what is wrong with my code? Thank you.
public class Rational implements Comparable<Rational>{
private int num; //numerator
private int denom; //denominator
public Rational() {
num = 0;
denom = 1;
}
public Rational(int num, int denom) {
if(denom <=0 ){
throw new ArithmeticException("You cannot divide by a non-positive number");
}
this.num = num;
this.denom = denom;
}
//returns numerator of this rational number
public int getNum() {
return num;
}
//returns denominator of this rational number
public int getDenom() {
return denom;
}
public Rational add(Rational rhs) {
return new Rational(num*rhs.denom+rhs.num*denom, denom*rhs.denom);
}
public Rational subtract(Rational rhs) {
return new Rational(num*rhs.denom-rhs.num*denom, denom*rhs.denom);
}
public Rational multiply(Rational rhs) {
return new Rational(num*rhs.num, denom*rhs.denom);
}
public Rational divide(Rational rhs) {
return new Rational(num*rhs.denom, denom*rhs.num);
}
public String toString() {
String result;
if (num == 0)
result = "0";
else if(denom == 1)
result = num + "";
else
result = num + "/" + denom;
return result;
}
public int compareTo(Rational rhs){
double r1 = ((double) getNum()/getDenom());
double r2 = ((double)rhs.getNum() / rhs.getDenom());
return (int) (r1 - r2);
}
public static void main(String[] args) {
Rational r1 = new Rational(1, 2); // 1/2
Rational r2 = new Rational(3, 4); // 3/4
Rational result = r1.add(r2);
Rational result1 = r1.subtract(r2);
Rational result2 = r1.multiply(r2);
Rational result3 = r1.divide(r2);
System.out.println( "r1 + r2 = " + result + "\n" + "r1 - r2 = " + result1 + "\n" + "r1*r2 = "+ result2 + "\n" + "r1/r2 = " + result3 + "\n" + (r1.compareTo(r2)));
}
}
This formula
return (int) (r1 - r2);
produces zero when the difference between r1 and r2 is less than 1, which is the case that you are testing.
Since both denominators are positive by construction of your class, you can cross-multiply and subtract without using division at all:
long a = (long)getNum() * rhs.getDenom();
long b = (long)rhs.getNum() * getDenom();
return Long.compare(a, b);
Use long to avoid overflowing on multiplication.

Fraction calculator input error [duplicate]

This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed 6 years ago.
I am working on a fraction calculator program for my AP Computer Science class. This code compiles and runs, however when I put in any input, besides quit, there is an error. With an input 8_9/4 + 3/7 there is an error of:
Exception in thread "main" java.lang.NumberFormatException: For input string: "4 + 3/7".
Can someone please help me figure out what's wrong?
import java.util.*;
public class FracCalc {
public static void main(String[] args) {
typeEquation();
}
public static void typeEquation() {
System.out.print("Enter an equation, or \"quit\" : ");
Scanner scan = new Scanner(System.in);
String fraction = scan.nextLine();
String secondOperator;
if (fraction.equalsIgnoreCase("quit")) {
finish();
}
else {
produceAnswer(fraction);
}
}
public static void produceAnswer(String fraction) {
int whole2;
int numerator2;
int denominator2;
int whole1;
int numerator1; //all caps identifier thing?
int denominator1;
String operator = fraction.substring((fraction.indexOf(" ")) + 1);
if (fraction.contains("_")) {
whole2 = Integer.parseInt(fraction.substring(0, fraction.indexOf("_")));
numerator2 = Integer.parseInt(fraction.substring(fraction.indexOf("_") + 1, fraction.indexOf("/")));
denominator2 = Integer.parseInt(fraction.substring(fraction.indexOf("/") + 1));
numerator2 = whole2 * denominator2 + numerator2;
}
else if (fraction.contains("/")) {
numerator2 = Integer.parseInt(fraction.substring(0,fraction.indexOf("/")));
denominator2 = Integer.parseInt(fraction.substring(fraction.indexOf("/") + 1));
}
else {
whole2 = Integer.parseInt(fraction.substring(0));
numerator2 = whole2;
denominator2 = 1;
}
if (fraction.contains("_")) {
whole1 = Integer.parseInt(fraction.substring(0, fraction.indexOf("_")));
numerator1 = Integer.parseInt(fraction.substring(fraction.indexOf("_") + 1, fraction.indexOf("/")));
denominator1 = Integer.parseInt(fraction.substring(fraction.indexOf("/") + 1));
numerator1 = (whole1*denominator1) + numerator1;
}
else if (fraction.contains("/")) {
numerator1 = Integer.parseInt(fraction.substring(0, fraction.indexOf("/")));
denominator1 = Integer.parseInt(fraction.substring(fraction.indexOf("/") + 1));
}
else {
whole1 = Integer.parseInt(fraction.substring(0));
numerator1 = whole1;
denominator1 = 1;
}
if (fraction.contains("_")) {
whole2 = Integer.parseInt(fraction.substring(0, fraction.indexOf("_")));
numerator2 = Integer.parseInt(fraction.substring(fraction.indexOf("_") + 1, fraction.indexOf("/")));
denominator2 = Integer.parseInt(fraction.substring(fraction.indexOf("/") + 1));
numerator2 = whole2 * denominator2 + numerator2;
}
else if (fraction.contains("/")) {
numerator2 = Integer.parseInt(fraction.substring(0, fraction.indexOf("/")));
denominator2 = Integer.parseInt(fraction.substring(fraction.indexOf("/") + 1));
}
else {
whole2 = Integer.parseInt(fraction.substring(0));
numerator2 = whole2;
denominator2 = 1;
}
if (operator.equals("+")) {
System.out.println(addingFractions(numerator1, numerator2, denominator1, denominator2));
}
else if (operator.equals("*")) {
System.out.println(multiplyingFractions(numerator1, numerator2, denominator1, denominator2));
}
else {
int x = numerator2;
int y = denominator2;
denominator2 = x;
numerator2 = y;
System.out.println(multiplyingFractions(numerator1, numerator2, denominator1, denominator2));
}
int dividend = (denominator1 * numerator2) + (numerator1 * denominator2);
int divisor = denominator1 * denominator2;
int remainder = dividend % divisor;
while (remainder != 0){
dividend = divisor;
divisor = remainder;
remainder = dividend % divisor;
}
}
public static String multiplyingFractions(int numerator1, int numerator2, int denominator1, int denominator2) {
int newNumerator = numerator1 * numerator2;
int newDenominator = denominator1 * denominator2;
int divisor = reducingFractions(newNumerator, newDenominator);
newNumerator /= divisor;
newDenominator /= divisor;
int integerComponent = 0;
while (newNumerator >= newDenominator) {
integerComponent++;
newNumerator -= newDenominator;
}
String answer = "";
if (integerComponent > 0) {
answer += integerComponent + "_";
}
if (newNumerator != 0) {
answer += reducingFractions(newNumerator, newDenominator);
}
return answer;
}
public static String addingFractions(int numerator1, int numerator2, int denominator1, int denominator2) {
int newNumerator = (numerator1 * denominator2) + (numerator2 * denominator1);
int newDenominator = denominator1 * denominator2;
int divisor = reducingFractions(newNumerator, newDenominator);
newNumerator /= divisor;
newDenominator /= divisor;
int integerComponent = 0;
while (newNumerator >= newDenominator) {
integerComponent++;
newNumerator -= newDenominator;
}
String answer = "";
if (integerComponent > 0) {
answer += integerComponent + "_";
}
if (newNumerator != 0) {
answer += newNumerator + "/" + newDenominator;
}
return answer;
}
public static int reducingFractions(int newNumerator, int newDenominator) {
int newNumerator_abs = Math.abs (newNumerator);
int newDenominator_abs = Math.abs (newDenominator);
int minimumNumber = Math.min (newNumerator_abs, newDenominator_abs);
int divisor = 1;
for (int i = 1; i <= minimumNumber; i++) {
if (newNumerator % i == 0 && newDenominator % i == 0){
divisor = 1;
}
}
return divisor;
}
public static void finish() {
System.out.println("Goodbye!");
}
}
You are getting this error, because you try to parse a String as integer, even if it isn't an integer. This is the problematic line:
denominator2 = Integer.parseInt(fraction.substring(fraction.indexOf("/") + 1));
for this input 8_9/4 + 3/7.
This fraction.indexOf("/") returns you the first occurrence of the slash. So, the following expression fraction.substring(fraction.indexOf("/") + 1) returns 4 + 3/7 which is not an integer, so it cannot be parsed using Integer.parseInt.
If you want to get only 4 instead of 4 + 3/7, you can replace your line with:
denominator2 = Integer.parseInt(fraction.substring(fraction.indexOf("/") + 1, fraction.indexOf(" ")));
You did not extract the "fraction" string correctly. Be careful when you do Integer.parseInt(). It doesn't take in equation.
In the code that you wrote:
else if (fraction.contains("/")) {
numerator2 = Integer.parseInt(fraction.substring(0,fraction.indexOf("/")));
denominator2 = Integer.parseInt(fraction.substring(fraction.indexOf("/") + 1));
}
The fraction.substring(0,fraction.indexOf("/") will return "8_9" as string. Which is not recognisable by Integer.parseInt.
Try to run in debug and set the breakpoint to break at Interger.parseInt for visualising the values.

Why does my code throw an ArithmeticException when I expect it to simply print "Error"?

I have made a program that asks the user to enter two numbers, and it should give an error if the second number is a 0. However, I am getting an error, which is below. I have an if-else statement but it's not doing what I expect it to. I'm not sure what I'm doing wrong.
public static void main(String[] args) {
int x, y;
Scanner kbd = new Scanner(System.in);
System.out.print("Enter a: ");
x = kbd.nextInt();
System.out.print("Enter b: ");
y = kbd.nextInt();
int result = add(x, y);
int result2 = sub(x, y);
int result3 = multi(x, y);
int result4 = divide(x, y);
int result5 = mod(x, y);
System.out.println(x + " + " + y + " = " + result);
System.out.println(x + " - " + y + " = " + result2);
System.out.println(x + " * " + y + " = " + result3);
System.out.println(x + " / " + y + " = " + result4);
System.out.print(x + " % " + y + " = " + result5);
}
public static int add(int x, int y) {
int result;
result = x + y;
return result;
}
public static int sub(int x, int y) {
int result2;
result2 = x - y;
return result2;
}
public static int multi(int x, int y) {
int result3;
result3 = x * y;
return result3;
}
public static int divide(int x, int y) {
int result4;
result4 = x / y;
if (y == 0) {
System.out.print("Error");
} else {
result4 = x / y;
}
return result4;
}
public static int mod(int x, int y) {
int result5;
result5 = x % y;
if (y == 0) {
System.out.print("Error");
} else {
result5 = x % y;
}
return result5;
}
Output
I get this error..
Enter a: 10
Enter b: 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
You get this because when you divide by 0, Java throws an Exception. If you just want to use an if statement to handle it, then use something like this:
public static int divide(int x, int y){
int result;
if ( y == 0 ) {
// handle your Exception here
} else {
result = x/y;
}
return result;
}
Java also handles Exceptions through try/catch blocks, which runs code in the try block and will handle how the exceptions are processed in the catch block. So you could do:
try {
result4 = divide(a, b);
}
catch(//the exception types you want to catch ){
// how you choose to handle it
}
Ok, I copied-pasted your code verbatim, surrounded it in a class, imported java.util.Scanner and run javac. For what I can see, you have two extras "}" at the end of your file. You also have other problems: result4 and result5 are not initialised and the compiler will go mad with you, because if y == 0 is true then the return values of divide and mod methods are undefined.
public static void main(String[] args) {
int x,y;
Scanner kbd = new Scanner(System.in);
System.out.print("Enter a: ");
x = kbd.nextInt();
System.out.print("Enter b: ");
y = kbd.nextInt();
int result = add(x,y);
int result2 = sub(x,y);
int result3 = multi(x,y);
int result4 = divide(x,y);
int result5 = mod(x,y);
System.out.println(x +" + "+ y +" = "+ result);
System.out.println(x +" - "+ y +" = "+ result2);
System.out.println(x +" * "+ y +" = "+ result3);
System.out.println(x +" / "+ y +" = "+ result4);
System.out.print(x +" % "+ y +" = "+ result5);
}
public static int add(int x, int y){
int result;
result = x+y;
return result;
}
public static int sub(int x, int y){
int result2;
result2 = x-y;
return result2;
}
public static int multi(int x, int y){
int result3;
result3 = x * y;
return result3;
}
public static int divide(int x, int y){
int result4;
result4 = 0;
if ( y == 0 ) {
System.out.print("Error");
}
else{
result4 = x/y;
}
return result4;
}
public static int mod(int x, int y){
int result5;
result5 = 0;
if ( y == 0) {
System.out.println("Error!");
}
else{
result5 = x % y;
}
return result5;
}
}
output
Enter a: 4
Enter b: 0
ErrorError!
4 + 0 = 4
4 - 0 = 4
4 * 0 = 0
4 / 0 = 0
4 % 0 = 0

What is wrong with my pi calculator?

I'm using Wallis' method to calculate pi, and I think I did it right. At least I thought I did anyway. I think the problem (output is 0)has to do with rounding and remainders, though I can't be sure. Here's the code:
import java.util.Scanner;
public class WallisPi {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = 2;
int b = 3;
int c = 1;
int pi = 0;
double acc = 0.0;
int n = scan.nextInt();
scan.close();
for (int i = 0; i <= n; i++) {
pi = (2 / 3) * c;
if (a > b) {
b += 2;
} else {
a += 2;
}
c = a / b;
}
pi *= 4;
System.out.println("The approximation of pi is " + pi + ".");
acc = Math.PI - pi;
System.out.println("It is " + acc + " off.");
}
}
Since posting this I've made some changes to the code, though it's still not quite functional. I get 2.666..., so there's something else at work here as well.
import java.util.Scanner;
public class WallisPi {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double a = 2.0;
double b = 3.0;
double c = 1.0;
double pi = 0;
double acc = 0.0;
int n = scan.nextInt();
scan.close();
for (int i = 0; i <= n; i++) {
pi = (2.0 / 3.0) * c;
if (a > b) {
b += 2;
} else {
a += 2;
}
c = a / b;
}
pi *= 4;
System.out.println("The approximation of pi is " + pi + ".");
acc = Math.PI - pi;
System.out.println("It is " + acc + " off.");
}
}
int a=2;
int b=3;
double pi=2;
for(int i=0;i<=n;i++){
pi *= (double)a/(double)b;
if(a>b){
b+=2;
} else {
a+=2;
}
}
pi*=2;
Using n = 4000 yields 3.141200
Here's the whole program, fixed:
import java.util.Scanner;
public class WallisPi {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
scan.close();
double pi = 2;
int a = 2;
int b = 3;
for (int i = 0; i <= n; i++){
pi *= (double) a / (double) b;
if (a > b) {
b += 2;
} else {
a += 2;
}
}
pi *= 2;
double acc = Math.PI - pi;
System.out.println("The approximation of pi is " + pi + ".");
System.out.println("It is " + acc + " off.");
}
}
Since your varibles are ints, all your divisions are integer divisions, omitting the fraction (and preserving only the whole part of the result). For accurate results, you should define your variables as doubles:
double a=2;
double b=3;
double c=1;
double pi=0;

Categories