Fraction-decimal(and vice versa) converter - java

I have 2 parts of code, the first one being converting fraction to decimal, and the second one being converting decimal to fraction.
However, I have to combine the two piece of code together and I have no idea.I want it to detect the input as either doubles or fraction and convert it to the other.
import java.util.*;
public class ExcerciseEleven {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter Numerator: ");
int numerator = sc.nextInt();
System.out.println("Enter Denominator: ");
int denominator = sc.nextInt();
if (denominator == 0) {
System.out.println("Can't divide by zero");
}
else {
double fraction = (double)numerator / denominator;
System.out.println(fraction);
}
}
}
public class Fractions {
public static void main(String args[]) {
double decimal;
double originalDecimal;
int LIMIT = 12;
int denominators[] = new int[LIMIT + 1];
int numerator, denominator, temp;
int MAX_GOODNESS = 100;
// Get a number to be converted to a fraction
if (args.length == 1) {
decimal = Double.valueOf(args[0]).doubleValue();
} else {
// No number was given, so just use pi
assert args.length == 0;
decimal = Math.PI;
}
originalDecimal = decimal;
// Display the header information
System.out.println("-------------------------------------------------------");
System.out.println("Program by David Matuszek");
System.out.println("Input decimal number to be converted: " + decimal);
System.out.println();
// Compute all the denominators
System.out.println("All computed denominators:");
int i = 0;
while (i < LIMIT + 1) {
denominators[i] = (int)decimal;
System.out.print(denominators[i] + " ");
decimal = 1.0 / (decimal - denominators[i]);
i = i + 1;
}
System.out.println();
System.out.println();
// Compute the i-th approximation
int last = 0;
while (last < LIMIT) {
// Print out the denominators used in this computation
System.out.print("Using these " + (last + 1) + " denominators: ");
for (int j = 0; j <= last; j++) {
System.out.print(denominators[j] + " ");
}
System.out.println();
// Initialize variables used in computation
numerator = 1;
denominator = 1;
temp = 0;
// Do the computation
int current = last;
while (current >= 0) {
denominator = numerator;
numerator = (numerator * denominators[current]) + temp;
temp = denominator;
current = current - 1;
}
last = last + 1;
// Display results
double value = (double)numerator/denominator;
int goodness = denominators[last];
double error = 100 * Math.abs(value - originalDecimal) / originalDecimal;
System.out.print("fraction = " + (int)numerator + "/" +
(int)denominator);
System.out.print(", value = " + value);
System.out.print(", goodness = " + goodness);
System.out.println(", error = " + (int)error + "%");
System.out.println();
// Exit early if we have reached our goodness criterion
if (Math.abs(goodness) > MAX_GOODNESS) break;
}
}
}

If I was doing it all on one prompt, I would make two static methods Fraction.TryParse(), and I would use the built in Double.TryParse(), if decimal.TryParse returns true then you do in fact have a decimal. If it returns false, then you have a Fraction, therefore you have to use the same string you passed into Decimal.TryParse() in Fraction.TryParse(). Of course you will need some sanity checks in your Fraction.TryParse() method. The prompt could look something like this:
Enter Decimal/Fraction: 3.14
Enter Decimal/Fraction: 1 + 1/2
Enter Decimal/Fraction: 1 1/2
Enter Decimal/Fraction: 1 (1/2)
You see, if you want this all on one line you need some way to be able to delimit the characters, like a space, or brackets, or simply a + sign which would be mathematically accurate. If it is all on one line it also simplifies your program a little bit because you don't have multiple prompts for one object. The "1 (1/2)" input is not technically mathematically accurate, but you can kind of see how the data is supposed to be structured, you just can't be mathematically rigid with that prompt.
Here I am using the fraction one and one half, your implementation doesn't have a mixed number implementation, but you could just input 1/2 or something, just regular fractions.

Related

Why does this java code to count digit of floating value goes in loop for this value?

import java.util.Scanner;
class FloatDigit {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double n = sc.nextDouble();
int x = (int) n;
int count = 0;
do {
count++;
x = x / 10;
} while (x != 0);
System.out.println("Before Decimal Digits: " + count);
//it gets stuck from here only
do {
count++;
n = n * 10;
} while (n != (int) n);
System.out.println(count + " total digits present in there in number.");
}
}
This goes in an infinite loop for the value: 58.2354/58.234. It is working fine with other values too and longer values too.
If some debug logging is added to the second loop, it can be seen, that when multiplying a double number by 10, there is a tiny error which does not allow the comparison n == (int) n ever become true.
It is actually a known issue that floating-point arithmetics has a certain computation error, so it should be taken into account when comparing the double n to its counterpart with the decimal point shifted right:
do {
count++;
n = n * 10;
System.out.println(count + " - " + n);
} while (Math.abs(n - (int) n) > 1E-7);
System.out.println(count + " total digits present in the number.");
Output:
58.234
Before Decimal Digits: 2
3 - 582.34
4 - 5823.400000000001
5 - 58234.00000000001
5 total digits present in the number.

My if statements will not take new values

The object is to get the average of the entered values.
It is to stop when a negative number is entered.
I am trying to get the smallest and largest values entered.
The problem I am having is that my if statements will not take the smallest/largest new values entered.
It just gives me the Integer.Max_Value and Integer.Min_Value.
import java.util.Scanner;
public class LargeSmallAverage {
public static void main(String[] args) {
// TODO Auto-generated method stub
double count = 0;
double amtOfNums = 0;
int input = 0;
int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE;
int number;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
Scanner scan = new Scanner(System.in);
while ((input = scan.nextInt()) > 0) {
count += input;
amtOfNums++;
}
while(input>=0){
for(int counter=1; counter<amtOfNums; counter++){
number=scan.nextInt();
if(number<smallest)
smallest=number;
if(number>largest)
largest=number;
}
}
System.out.println("You entered " + amtOfNums + " numbers averaging " + (count/amtOfNums) + ".");
System.out.println("The smallest number is "+ smallest);
System.out.println("The largest number is " + largest);
}
}
Currently you have two loops. One sums the numbers, and the other finds the largest and smallest numbers. Given your output, it sounds like you should be doing it all in one loop - ideally with more useful variable names too. (Your count is actually a sum, not a count... and there's no need for it to be a double. You could make it a long if you really want to avoid overflow. Yes, you need to perform floating point arithmetic for your average, but you can do that when you take the average... your sum is logically an integer.)
int sum = 0;
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
int count = 0;
while ((input = scan.nextInt()) >= 0) {
count++;
sum += input;
// Alternative: smallest = Math.min(smallest, input)
if (input < smallest) {
smallest = input;
}
// Alternative: largest = Math.max(smallest, input)
if (input > largest) {
largest = input;
}
}
// Cast for count is just to force floating point division.
System.out.println("You entered " + count +
" numbers averaging " + (sum / (double) count) + ".");
System.out.println("The smallest number is "+ smallest);
System.out.println("The largest number is " + largest);
There is a problem with your while loop condition: while(input>=0){
here input will be always less than zero due to your previous while statement:while ((input = scan.nextInt()) > 0)
Here while loop exits only when you enter a number which is less than zero.. so input will have that value..

Recursion - Java

I am working on a program where I have to use recursion to calculate the sum of 1/3 + 2/5 + 3/7 + 4/9 + ... + i / (2i + 1). However, I am not sure how to make my program show the term that must be added in order to reach the number enter by the user. For example. If I enter 12, I want to know how many terms of the series [1/3 + 2/5 + 3/7 + 4/9 + ... + i / (2i + 1)] were added to get approximately to the number 12.
What I don't want to get is the sum of inputting 12 which in this case is 5.034490247342584 rather I want to get the term that if I were to sum all numbers up to that term I would get something close to 12.
Any help will be greatly appreciated!
This is my code
import java.util.Scanner;
public class Recursion {
public static void main(String[] args) {
double number;
Scanner input = new Scanner(System.in);
System.out.println("Enter a value= ");
number = input.nextInt();
System.out.println(sum(number) + " is the term that should be added in order to reach " + number);
}
public static double sum(double k) {
if (k == 1)
return 1/3;
else
return ((k/(2*k+1))+ sum(k-1));
}
}
You have this question kind of inside out. If you want to know how many terms you need to add to get to 12, you'll have to reverse your algorithm. Keep adding successive k / (2k + 1) for larger and larger k until you hit your desired target. With your current sum method, you would have to start guessing at starting values of k and perform a sort of "binary search" for an acceptably close solution.
I don't think that this problem should be solved using recursion, but... if you need to implement it on that way, this is a possible solution:
import java.util.Scanner;
public class Recursion {
public static void main(String[] args) {
double number;
Scanner input = new Scanner(System.in);
System.out.println("Enter a value= ");
number = input.nextInt();
double result = 0;
double expectedValue = number;
int k = 0;
while (result < expectedValue) {
k++;
result = sum(k);
}
System.out.println(k
+ " is the term that should be added in order to reach "
+ number + " (" + sum(k) + ")");
}
public static double sum(double k) {
if (k == 1)
return 1 / 3;
else
return ((k / (2 * k + 1)) + sum(k - 1));
}
}

How does this prime number test in Java work?

The code snippet below checks whether a given number is a prime number. Can someone explain to me why this works? This code was on a study guide given to us for a Java exam.
public static void main(String[] args)
{
int j = 2;
int result = 0;
int number = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter a number: ");
number = reader.nextInt();
while (j <= number / 2)
{
if (number % j == 0)
{
result = 1;
}
j++;
}
if (result == 1)
{
System.out.println("Number: " + number + " is Not Prime.");
}
else
{
System.out.println("Number: " + number + " is Prime. ");
}
}
Overall theory
The condition if (number % j == 0) asks if number is exactly divisible by j
The definition of a prime is
a number divisible by only itself and 1
so if you test all numbers between 2 and number, and none of them are exactly divisible then it is a prime, otherwise it is not.
Of course you don't actually have to go all way to the number, because number cannot be exactly divisible by anything above half number.
Specific sections
While loop
This section runs through values of increasing j, if we pretend that number = 12 then it will run through j = 2,3,4,5,6
int j = 2;
.....
while (j <= number / 2)
{
........
j++;
}
If statement
This section sets result to 1, if at any point number is exactly divisible by j. result is never reset to 0 once it has been set to 1.
......
if (number % j == 0)
{
result = 1;
}
.....
Further improvements
Of course you can improve that even more because you actually need go no higher than sqrt(number) but this snippet has decided not to do that; the reason you need go no higher is because if (for example) 40 is exactly divisible by 4 it is 4*10, you don't need to test for both 4 and 10. And of those pairs one will always be below sqrt(number).
It's also worth noting that they appear to have intended to use result as a boolean, but actually used integers 0 and 1 to represent true and false instead. This is not good practice.
I've tried to comment each line to explain the processes going on, hope it helps!
int j = 2; //variable
int result = 0; //variable
int number = 0; //variable
Scanner reader = new Scanner(System.in); //Scanner object
System.out.println("Please enter a number: "); //Instruction
number = reader.nextInt(); //Get the number entered
while (j <= number / 2) //start loop, during loop j will become each number between 2 and
{ //the entered number divided by 2
if (number % j == 0) //If their is no remainder from your number divided by j...
{
result = 1; //Then result is set to 1 as the number divides equally by another number, hergo
} //it is not a prime number
j++; //Increment j to the next number to test against the number you entered
}
if (result == 1) //check the result from the loop
{
System.out.println("Number: " + number + " is Not Prime."); //If result 1 then a prime
}
else
{
System.out.println("Number: " + number + " is Prime. "); //If result is not 1 it's not a prime
}
It works by iterating over all number between 2 and half of the number entered (since any number greater than the input/2 (but less than the input) would yield a fraction). If the number input divided by j yields a 0 remainder (if (number % j == 0)) then the number input is divisible by a number other than 1 or itself. In this case result is set to 1 and the number is not a prime number.
Java java.math.BigInteger class contains a method isProbablePrime(int certainty) to check the primality of a number.
isProbablePrime(int certainty): A method in BigInteger class to check if a given number is prime.
For certainty = 1, it return true if BigInteger is prime and false if BigInteger is composite.
Miller–Rabin primality algorithm is used to check primality in this method.
import java.math.BigInteger;
public class TestPrime {
public static void main(String[] args) {
int number = 83;
boolean isPrime = testPrime(number);
System.out.println(number + " is prime : " + isPrime);
}
/**
* method to test primality
* #param number
* #return boolean
*/
private static boolean testPrime(int number) {
BigInteger bValue = BigInteger.valueOf(number);
/**
* isProbablePrime method used to check primality.
* */
boolean result = bValue.isProbablePrime(1);
return result;
}
}
Output: 83 is prime : true
For more information, see my blog.
Do try
public class PalindromePrime {
private static int g ,k ,n =0,i,m ;
static String b ="";
private static Scanner scanner = new Scanner( System.in );
public static void main(String [] args) throws IOException {
System.out.print(" Please Inter Data : ");
g = scanner.nextInt();
System.out.print(" Please Inter Data 2 : ");
m = scanner.nextInt();
count(g,m);
}
//
//********************************************************************************
private static int count(int L, int R)
for( i= L ; i<= R ;i++){
int count = 0 ;
for( n = i ; n >=1 ;n -- ){
if(i%n==0){
count = count + 1 ;
}
}
if(count == 2)
{
b = b +i + "" ;
}
}
System.out.print(" Data : ");
System.out.print(" Data : \n " +b );
return R;
}
}

Probability of three floating point numbers

How can I implement this into code I am taking a user input of three separate floats that must add to one (ie .333333,.333333,.333333) those numbers are the probability of a number (-1,0,1) being picked at random.
if( new Random().nextDouble() <= 0.333334){array[i]=randomNumber(-1,0,1)?
Or something along those lines?
The likelihood that three floats will add to exactly 1.0 is very low, because many (most) real numbers cannot be represented exactly as floats. The best you could do is enter two numbers and calculate the third, which would guarantee that they would add up to 1.0.
public static void main(String[] args) {
double[] probs = readProbabilities();
double random = new Random().nextDouble();
int randomNumber;
if (random <= probs[0]) {
randomNumber = -1;
} else if (random <= (probs[0] + probs[1])) {
randomNumber = 0;
} else {
randomNumber = 1;
}
System.out.println("Random Number is " + randomNumber);
}
public static double[] readProbabilities() {
Scanner sc = new Scanner(System.in);
double first, second, third;
System.out.print("Please insert 1st probability: ");
first = sc.nextDouble();
while (first < 0.0 || first > 1.0) {
System.out.print("Must be between 0.0 and 1.0, try again: ");
first = sc.nextDouble();
}
System.out.print("Please insert 2nd probability: ");
second = sc.nextDouble();
while (second < 0.0 || (first + second) > 1.0 ) {
System.out.print("Must be between 0.0 and " + (1.0 - first) + ":");
second = sc.nextDouble();
}
third = 1.0 - (first + second);
System.out.println("3rd Possibility is " + third);
return new double[] {first, second, third};
}
Questions?

Categories