Converting to a fraction - java

Trying to convert a decimal into a fraction and provide its reciprocal
This is for Java. I tried multiple methods and doing a Math.pow, it is a bit complicated when I already have the answer in decimal form only want to convert it and have the program give the reciprocal
public class ParallelSeriesCircuit {
public static final int SERIES = 1;
public static final int PARALLEL = 2;
public int circuitType;
public double[] resistance;
public double Rtotal;
public int Rseries;
public int getNumberOfResistors() {
return resistance.length;
}
public double getTotalResistance() {
if (circuitType == SERIES) {
return getSeriesResistance();
} else {
return getParallelResistance();
}
}
public double getParallelResistance() {
int i = 0;
for (i = 0; i < resistance.length; i++) {
Rtotal += 1 / resistance[i];
}
return Rtotal;
}
private double getSeriesResistance() {
for (int i = 0; i < resistance.length; i++) {
Rtotal += resistance[i];
}
return Rtotal;
}
}
The problem lies in method getParallelResistance as I can't seem to figure out a conversion to a fraction. This is based on user input so that makes it even more complicated

Formula for Series Resistance is R = R1 + R2 + R3 + ... and is correctly calculated by getSeriesResistance().
Formula for Parallel Resistance is 1 / R = 1 / R1 + 1 / R2 + 1 / R3 +... but that is not what getParallelResistance() calculates.
Change to return 1 / Rtotal;
Also, you need to make Rtotal a local variable:
public double getParallelResistance() {
double sum = 0;
for (double r : resistance) {
sum += 1 / r;
}
return 1 / sum;
}
private double getSeriesResistance() {
double sum = 0;
for (double r : resistance) {
sum += r;
}
return sum;
}

Related

Using two methods in a class (Rational) to simplify a fraction

I have a class definition for a class of rational numbers. My assignment is to be able to add, multiply and divide any fraction I put in my main function. My program can do all that, but I'm having trouble simplifying the fractions. I want to try and use only two methods to simplify, for example public void reduce(); and private static gcd();
public class Rational {
private int num;
private int denom;
public Rational() {
num = 0;
denom = 1;
}
public Rational(int n, int d) {
num = n;
denom = d;
reduce();
}
public Rational plus(Rational t) {
int tnum = 0;
int tdenom = 1;
tnum = (this.num * t.denom) + (this.denom * t.num);
tdenom = (t.denom * this.denom);
Rational r = new Rational (tnum, tdenom);
return r;
}
public Rational minus(Rational t) {
int tnum = 0;
int tdenom = 1;
tnum = (this.num * t.denom) - (this.denom * t.num);
tdenom = (t.denom * this.denom);
Rational r = new Rational (tnum, tdenom);
return r;
}
public Rational multiply(Rational t) {
int tnum = 0;
int tdenom = 1;
tnum = this.num * t.num;
tdenom = t.denom * this.denom;
Rational r = new Rational (tnum, tdenom);
return r;
}
public Rational divide(Rational t) {
int tnum = 0;
int tdenom = 1;
tnum = this.num / t.num;
tdenom = this.denom / t.denom;
Rational r = new Rational (tnum, tdenom);
return r;
}
private static int gcd(int n, int d) {
return gcd(d, n%d);
}
public void reduce() {
//call gcd
gcd(num, denom);
//divide num and denom by gcd by
num = num / gcd(num,denom);
denom = denom / gcd(num,denom);
}
public String toString() {
return String.format("%d/%d", num, denom);
}
}
public class RationalMain {
public static void main(String[] args) {
Rational x = new Rational();
Rational y = new Rational(1,4);
Rational z = new Rational(1,2);
//x = y - z;
x = y.plus(z);
System.out.printf("%s = %s + %s\n", x.toString(), y.toString(), z.toString());
x = z.minus(y);
System.out.printf("%s = %s - %s\n", x.toString(), z.toString(), y.toString());
x = z.multiply(y);
System.out.printf("%s = %s * %s\n", x.toString(), z.toString(), y.toString());
x = y.divide(z);
System.out.printf("%s = %s / %s\n", x.toString(), y.toString(), z.toString());
}
}
That's not how you might achieve the Greatest Common Divisor (GCD). Before you will be able to get your code to work properly you will need to at least fix your gcd() method since currently it will recurse until an ArithmeticException (/ by zero) is generated. You might achieve the task this way:
private static int gcd(int num, int den) {
num = Math.abs(num); // if numerator is signed convert to unsigned.
int gcd = Math.abs(den); // if denominator is signed convert to unsigned.
int temp = num % gcd;
while (temp > 0) {
num = gcd;
gcd = temp;
temp = num % gcd;
}
return gcd;
}
To convert your fractions too their Lowest Terms your reduce() method might look like this if it accepted a Fraction String as an argument (you modify the method parameters if you like):
/*
A Fraction String can be supplied as: "1/2", or "2 1/2", or
"2-1/2, or "-2 32/64", or "-2-32/64". The last 2 examples are
negative fraction values.
*/
private String reduce(String fractionString) {
// Fraction can be supplied as: "1/2", or "2 1/2", or "2-1/2".
// Make sure it's a Fraction String that was supplied as argument...
inputString = inputString.replaceAll("\\s+", " ").trim();
if (!inputString.matches("\\d+\\/\\d+|\\d+\\s+\\d+\\/\\d+|\\d+\\-\\d+\\/\\d+")) {
return null;
}
str2 = new StringBuilder();
String wholeNumber, actualFraction;
if (inputString.contains(" ")) {
wholeNumber = inputString.substring(0, inputString.indexOf(" "));
actualFraction = inputString.substring(inputString.indexOf(" ") + 1);
str2.append(wholeNumber);
str2.append(" ");
}
else if (inputString.contains("-")) {
wholeNumber = inputString.substring(0, inputString.indexOf("-"));
actualFraction = inputString.substring(inputString.indexOf("-") + 1);
str2.append(wholeNumber);
str2.append("-");
}
else {
actualFraction = inputString;
}
String[] tfltParts = actualFraction.split("\\/");
int tfltNumerator = Integer.parseInt(tfltParts[0]);
int tfltDenominator = Integer.parseInt(tfltParts[1]);
// find the larger of the numerator and denominator
int tfltN = tfltNumerator;
int tfltD = tfltDenominator;
int tfltLargest;
if (tfltNumerator < 0) {
tfltN = -tfltNumerator;
}
if (tfltN > tfltD) {
tfltLargest = tfltN;
}
else {
tfltLargest = tfltD;
}
// Find the largest number that divides the numerator and
// denominator evenly
int tfltGCD = 0;
for (int tlftI = tfltLargest; tlftI >= 2; tlftI--) {
if (tfltNumerator % tlftI == 0 && tfltDenominator % tlftI == 0) {
tfltGCD = tlftI;
break;
}
}
// Divide the largest common denominator out of numerator, denominator
if (tfltGCD != 0) {
tfltNumerator /= tfltGCD;
tfltDenominator /= tfltGCD;
}
str2.append(String.valueOf(tfltNumerator)).append("/").append(String.valueOf(tfltDenominator));
return str2.toString();
}
As you can see, a whole number can also be supplied with your fraction so, if you do a call to the above reduce() method like this:
System.out.println(reduce("12-32/64"));
System.out.println(reduce("12 32/64"));
The console window will display:
12-1/2
12 1/2

Java Program to determine value of nested radical constant with 10^-6 precision

Nested radical constant is defined as:
I am writing a Java program to calculate the value of nested radical constant with 10^-6 precision and also print the number of iterations required to get to that precision. Here is my code:
public class nested_radical {
public nested_radical() {
int n = 1;
while ((loop(n) - loop(n - 1)) > 10e-6) {
n++;
}
System.out.println("value of given expression = " + loop(n));
System.out.println("Iterations required = " + n);
}
public double loop(int n) {
double sum = 0;
while (n > 0) {
sum = Math.sqrt(sum + n--);
}
return (sum);
}
public static void main(String[] args) {
new nested_radical();
}
}
This code does what it is supposed to but it is slow. What should I do to optimize this program? Can someone suggest another possible way to implement this program?
I also want to write a same kind of program in MATLAB. It would be great if someone could translate this program into MATLAB too.
I have made some changes in this code and now it stores the value of loop(n - 1) instead of computing it every time. Now this program seems much optimized than before.
public class nested_radical {
public nested_radical() {
int n = 1;
double x = 0, y = 0, p = 1;
while ( p > 10e-6) {
y=x; /*stored the value of loop(n - 1) instead of recomputing*/
x = loop(n);
p = x - y;
n++;
}
System.out.println("value of given expression = " + x);
System.out.println("Iterations required = " + n);
}
public double loop(int n) {
double sum = 0;
while (n > 0) {
sum = Math.sqrt(sum + n--);
}
return (sum);
}
public static void main(String[] args) {
new nested_radical();
}
}
I also successfully translated this code in MATLAB. Here is the code for MATLAB:
n = 1;
x = 0;
p = 1;
while(p > 10e-6)
y = x;
sum = 0;
m=n;
while (m > 0)
sum = sqrt(sum + m);
m = m - 1;
end
x = sum;
p = (x-y);
n = n + 1;
end
fprintf('Value of given expression: %.16f\n', x);
fprintf('Iterations required: %d\n', n);

Calling a class in Android Studio

I have created in android studio an app that changes numbers from base 10 to base 2. I have created the algorithm below, but I have trouble calling the class and getting it to print the result.
Can anyone help me ? Thanks in advance.
This is my code,
public class baseconv {
float m = Float.parseFloat(number.getText().toString());
int n = (int) m;
int pow = 1;
int x = 0;
public void calculate () {
while (n > 0) {
x = x + (n % 2)*pow;
n = n / 2;
pow = pow * 10;
}
}
}
To convert integer in base 10 to base 2 try this,
String baseTwoString = Integer.toString(your_integer, 2);
But if you are particular that you need to use your custom algorithm read on.
In your Activity,
String input = number.getText().toString();
try {
int n = (int) Float.parseFloat(input);
BaseConvert converter = new BaseConvert();
int output = converter.calculate(n);
Log.e("output : ", output);
} catch(NumberFormatException e) {
e.printStackTrace();
}
Your converter class,
public class BaseConvert {
public int calculate (int n) {
int pow = 1;
int x = 0;
while (n > 0) {
x = x + (n % 2) * pow;
n = n / 2;
pow = pow * 10;
}
return pow;
}
}

how to get exponents without using the math.pow for java

This is my program
// ************************************************************
// PowersOf2.java
//
// Print out as many powers of 2 as the user requests
//
// ************************************************************
import java.util.Scanner;
public class PowersOf2 {
public static void main(String[] args)
{
int numPowersOf2; //How many powers of 2 to compute
int nextPowerOf2 = 1; //Current power of 2
int exponent= 1;
double x;
//Exponent for current power of 2 -- this
//also serves as a counter for the loop Scanner
Scanner scan = new Scanner(System.in);
System.out.println("How many powers of 2 would you like printed?");
numPowersOf2 = scan.nextInt();
System.out.println ("There will be " + numPowersOf2 + " powers of 2 printed");
//initialize exponent -- the first thing printed is 2 to the what?
while( exponent <= numPowersOf2)
{
double x1 = Math.pow(2, exponent);
System.out.println("2^" + exponent + " = " + x1);
exponent++;
}
//print out current power of 2
//find next power of 2 -- how do you get this from the last one?
//increment exponent
}
}
The thing is that I am not allowed to use the math.pow method, I need to find another way to get the correct answer in the while loop.
Powers of 2 can simply be computed by Bit Shift Operators
int exponent = ...
int powerOf2 = 1 << exponent;
Even for the more general form, you should not compute an exponent by "multiplying n times". Instead, you could do Exponentiation by squaring
Here is a post that allows both negative/positive power calculations.
https://stackoverflow.com/a/23003962/3538289
Function to handle +/- exponents with O(log(n)) complexity.
double power(double x, int n){
if(n==0)
return 1;
if(n<0){
x = 1.0/x;
n = -n;
}
double ret = power(x,n/2);
ret = ret * ret;
if(n%2!=0)
ret = ret * x;
return ret;
}
You could implement your own power function.
The complexity of the power function depends on your requirements and constraints.
For example, you may constraint exponents to be only positive integer.
Here's an example of power function:
public static double power(double base, int exponent) {
double ans = 1;
if (exponent != 0) {
int absExponent = exponent > 0 ? exponent : (-1) * exponent;
for (int i = 1; i <= absExponent; i++) {
ans *= base;
}
if (exponent < 0) {
// For negative exponent, must invert
ans = 1.0 / ans;
}
} else {
// exponent is 0
ans = 1;
}
return ans;
}
If there are no performance constraints you can do:
double x1=1;
for(int i=1;i<=numPowersOf2;i++){
x1 =* 2
}
You can try to do this based on this explanation:
public double myPow(double x, int n) {
if(n < 0) {
if(n == Integer.MIN_VALUE) {
n = (n+1)*(-1);
return 1.0/(myPow(x*x, n));
}
n = n*(-1);
return (double)1.0/myPow(x, n);
}
double y = 1;
while(n > 0) {
if(n%2 == 0) {
x = x*x;
}
else {
y = y*x;
x = x*x;
}
n = n/2;
}
return y;
}
It's unclear whether your comment about using a loop is a desire or a requirement. If it's just a desire there is a math identity you can use that doesn't rely on Math.Pow.
xy = ey∙ln(x)
In Java this would look like
public static double myPow(double x, double y){
return Math.exp(y*Math.log(x));
}
If you really need a loop, you can use something like the following
public static double myPow(double b, int e) {
if (e < 0) {
b = 1 / b;
e = -e;
}
double pow = 1.0;
double intermediate = b;
boolean fin = false;
while (e != 0) {
if (e % 2 == 0) {
intermediate *= intermediate;
fin = true;
} else {
pow *= intermediate;
intermediate = b;
fin = false;
}
e >>= 1;
}
return pow * (fin ? intermediate : 1.0);
}
// Set the variables
int numPowersOf2; //How many powers of 2 to compute
int nextPowerOf2 = 1; //Current power of 2
int exponent = 0;
/* User input here */
// Loop and print results
do
{
System.out.println ("2^" + exponent + " = " + nextPowerOf2);
nextPowerOf2 = nextPowerOf2*2;
exponent ++;
}
while (exponent < numPowersOf2);
here is how I managed without using "myPow(x,n)", but by making use of "while". (I've only been learning Java for 2 weeks so excuse, if the code is a bit lumpy :)
String base ="";
String exp ="";
BufferedReader value = new BufferedReader (new InputStreamReader(System.in));
try {System.out.print("enter the base number: ");
base = value.readLine();
System.out.print("enter the exponent: ");
exp = value.readLine(); }
catch(IOException e){System.out.print("error");}
int x = Integer.valueOf(base);
int n = Integer.valueOf(exp);
int y=x;
int m=1;
while(m<n+1) {
System.out.println(x+"^"+m+"= "+y);
y=y*x;
m++;
}
To implement pow function without using built-in Math.pow(), we can use the below recursive way to implement it. To optimize the runtime, we can store the result of power(a, b/2) and reuse it depending on the number of times is even or odd.
static float power(float a, int b)
{
float temp;
if( b == 0)
return 1;
temp = power(a, b/2);
// if even times
if (b%2 == 0)
return temp*temp;
else // if odd times
{
if(b > 0)
return a * temp * temp;
else // if negetive i.e. 3 ^ (-2)
return (temp * temp) / a;
}
}
I know this answer is very late, but there's a very simple solution you can use if you are allowed to have variables that store the base and the exponent.
public class trythis {
public static void main(String[] args) {
int b = 2;
int p = 5;
int r = 1;
for (int i = 1; i <= p; i++) {
r *= b;
}
System.out.println(r);
}
}
This will work with positive and negative bases, but not with negative powers.
To get the exponential value without using Math.pow() you can use a loop:
As long as the count is less than b (your power), your loop will have an
additional "* a" to it. Mathematically, it is the same as having a Math.pow()
while (count <=b){
a= a* a;
}
Try this simple code:
public static int exponent(int base, int power) {
int answer = 1;
for(int i = 0; i < power; i++) {
answer *= base;
}
return answer;
}

Dividing longs which are returned by method - wrong values

I have two methods: power and factorial:
public static long pow(int x, int n) {
long p = x;
for (int i = 1; i < n; i++) {
p *= x;
}
return p;
}
public static long fact(int n) {
long s = n;
for (int i = 1; i < n; i++ ) {
s *= i;
}
return s;
}
that are returning longs. When I want to use them in new method evaluating Exponential function i get wrong results comparing to Math.exp(x). My code:
public static void exp(int x, double eps) {
int i = 1;
double pow = 1.0;
double fact = 1.0;
double sum = 0.0;
double temp;
do {
temp = pow/fact;
sum += temp;
pow = pow(x, i);
fact = fact(i);
i++;
}
while (temp > eps);
System.out.println("Check: " + Math.exp(x));
System.out.println("My: " + sum);
}
public static void main() {
int x = 10;
double eps = 0.0000000000001;
exp(x, eps);
}
and the output for x=10 is:
Check: 22026.465794806718
My: 21798.734894914145
the larger x, the bigger "loss of precision" (not exactly, because you can't really call it precise...).
The twist is, when methods power and factorial return double then the output is correct. Can anyone explain me how to make it work?
Methods pow and fact must return long and I must use them in exp (college assignment).
If you try this pow method:
public static long pow(int x, int n) {
long p = x;
System.out.println("Pow: "+x+","+n);
for (int i = 1; i < n; i++) {
p *= x;
System.out.println(p);
}
return p;
}
You get this output:
...
Pow: 10,20
100
1000
10000
...
...
1000000000000000
10000000000000000
100000000000000000
1000000000000000000
-8446744073709551616
7766279631452241920
The long value overflows: 10^20 is just too big to fit in a long.
Methods pow and fact must return long and I must use them in exp (college assignment).
Then there is not much you can do to fix it. You could throw an exception if eps is too small.
How large is x typically? It could be integer overflow. Try changing all the int arguments in pow and fact to be long instead.
Long data types can't handle decimal precision that's why you're values are wrong with long. Why don't you just have the functions return the double values?
Edit: Heres what I came up with:
public static long pow(int x, int n)
{
double p = x;
for (int i = 1; i < n; i++) {
p *= x;
}
return (long)p;
}
public static long fact(int n)
{
double s = n;
for (int i = 1; i < n; i++ ) {
s *= i;
}
return (long)s;
}
public static void exp(int x, double eps)
{
double pow = 1.0;
double fact = 1.0;
double sum = 0.0;
double temp;
for(int ii=1; ii < 100; ii++)
{
pow = pow(x, ii);
fact = fact(ii);
temp = (double)pow/(double)fact;
temp = temp == 1 ? 0 : temp;
sum += temp;
}
System.out.println("Check: " + Math.exp(x));
System.out.println("My: " + sum);
}
public static void main(final String[] args)
{
int x = 10;
double eps = 0.0000000000001;
exp(x, eps);
}
That's about the closest you're going to get without using the decimals.
Check: 22026.465794806718
My: 21946.785573087538

Categories