Working on a problem and got the Fahrenheit list that I need but I don't really know how to add another list next to it and have it do the math as well. Please help, Thank you.
The Problem:
A program that generates a two-column table showing Fahrenheit temperatures from -40F to 120F and their equivalent Celsius temperatures. Each line in the table should be 5 degrees F more than the previous one. Both the Fahrenheit and Celsius temperatures should be accurate to 1 decimal place.
My Attempt:
package chapter5;
public class Assignment2 {
public static void main(String[] args) {
//T(°C) = (T(°F) - 32) × 5/9
int F = 120;
int count = 0;
int C = (F - 32) * (5/9);
while (F >= -40 && F <= 120 ){
if (F % 5 == 0){
System.out.printf("%-5d",F);
count++;
}
if (count == 1){
System.out.println();
count = 0;
}
F--;
}
}
}
/* package whatever; // don't place package name! */
package chapter5;
/* Name of the class has to be "Main" only if the class is public. */
public class Assignment2 {
public static void main(String[] args) {
//T(°C) = (T(°F) - 32) × 5/9
final String DEGREE = "\u00b0";
int F = -40;
float C = 0.0F;
while (F <= 120 ){
C = (F - 32)*(0.5556F);
System.out.printf("%d%sF \t\t\t%.1f%sC\n", F, DEGREE, C, DEGREE);
F = F + 5;
}
}
}
Output
-40°F -40.0°C
-35°F -37.2°C
-30°F -34.4°C
-25°F -31.7°C
-20°F -28.9°C
-15°F -26.1°C
-10°F -23.3°C
-5°F -20.6°C
0°F -17.8°C
5°F -15.0°C
10°F -12.2°C
15°F -9.4°C
20°F -6.7°C
25°F -3.9°C
30°F -1.1°C
35°F 1.7°C
40°F 4.4°C
45°F 7.2°C
50°F 10.0°C
55°F 12.8°C
60°F 15.6°C
65°F 18.3°C
70°F 21.1°C
75°F 23.9°C
80°F 26.7°C
85°F 29.4°C
90°F 32.2°C
95°F 35.0°C
100°F 37.8°C
105°F 40.6°C
110°F 43.3°C
115°F 46.1°C
120°F 48.9°C
Look at printf format specification to print out in a tab mode both the F and C temperatures.
Also you need to do your calculations in a float or a double.
And you can write your loop in increments of 5 instead of looping through everything and checking for %5.
I used System.out.printf to format output in eclipse console.
public static void main(String[] args) {
double F = -40;
for (; F < 120; F += 5) {
double C = (F - 32) * 5 / 9;
C = BigDecimal.valueOf(C).setScale(1,RoundingMode.CEILING).doubleValue();
System.out.printf("%-10s %-10s \n", F, C);
}
}
This program takes one Farenheit value converts it to celsium, prints both in two columns and increments farenheit value by 5 and converts it to celsium again.
It uses java.lang.BigDecimal to round double value to 1 decimal place. This is done in method setScale(1,RoundingMode.CEILING)
I just have a for loop where I decrement by five, so I don't have to check if it could be divided by five.
In my solution, I convert from fahrenheit directly before printing.
Suggested by #Scary Wombat I used %.1f%n to display the celsius temperature with one decimal line place and a line separator.
Update: Added "\u00b0F" and "\u00b0C" to add the Strings °F and °C
public static void main(String[] args) {
//T(°C) = (T(°F) - 32) × 5/9
for (int F = 120;F >= -40; F-=5){
System.out.printf("%-3d\u00b0F %.1f\u00b0C%n",F, (double) ((F - 32d) * 5/9));
}
}
How about this:
// Each Celsius degree is calculated in the cycle.
double CasDouble = (F - 32.) * (5./9.);
// The double value is rounded to an integer
int C = (int) CasDouble;
// The application prints the Fahrenheit and Celsius degrees
System.out.printf("%-5d\t%-5d",F,C);
So:
package chapter5;
public class Assignment2 {
public static void main(String[] args) {
// T(°C) = (T(°F) - 32) × 5/9
int F = 120;
int count = 0;
while (F >= -40 && F <= 120) {
if (F % 5 == 0) {
// Each Celsius degree is calculated in the cycle.
double CasDouble = (F - 32.) * (5. / 9.);
// The double value is rounded to an integer
int C = (int) CasDouble;
// The application prints the Fahrenheit and Celsius degrees
System.out.printf("%-5d\t%-5d", F, C);
count++;
}
if (count == 1) {
System.out.println();
count = 0;
}
F--;
}
}
}
Related
excepted output : 1/4,1/2,3/4,1,5/4,3/2
but my output is coming as in the decimal form . Please help how to print in the form of fraction only.
import java.util.*;
public class Hello {
public static void main(String[] args) {
//Your Code Here
Scanner s=new Scanner(System.in);
int n=s.nextInt();
double d=1/4.0,sum=0;
for(int i=0;i<n;i++) {
sum+=d;
System.out.print(sum+" ");
}
}}
take input in form of string so it will take input in required format and split it by "/" i.e someString.spit("/").
after that make one for loop and take two number and in two different variable store it.
and then take division for both and print it by using "/" in between them.
public class NewClass {
public static void main(String[] args) {
System.out.println(convertype(0.75));
}
public static String convertype(double decimal){
int digitsAfterPoint = String.valueOf(decimal).length() - String.valueOf(decimal).indexOf('.')+1; // get the count of digits after the point // for example 0.75 has two digits
BigInteger numerator = BigInteger.valueOf((long)(decimal*Math.pow(10, digitsAfterPoint))); // multiply 0.75 with 10^2 to get 75
BigInteger denominator = BigInteger.valueOf((long)(Math.pow(10, digitsAfterPoint))); // 10^2 is your denominator
int gcd = numerator.gcd(denominator).intValue(); // calculate the greatest common divisor of numerator and denominator
if (gcd > 1 ){ // gcd(75,100) = 25
return String.valueOf(numerator.intValue()/gcd) +" / " + String.valueOf(denominator.intValue()/gcd); // return 75/25 / 100/25 = 3/4
}
else{
return String.valueOf(numerator) +" / " + String.valueOf(denominator); // if gcd = 1 which means nothing to simplify just return numerator / denominator
}
}
}
Wrote a method where you can convert double numbers to fraction. Use this to convert it and print as below,
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
double d=1/4.0,sum=0;
for(int i=0;i<n;i++) {
sum+=d;
System.out.print(toFraction(sum)+" ");
}
}
static String toFraction(double x) {
int w = (int) x;
int n = (int) (x * 64) % 64;
int a = n & -n;
return n == 0 ? w+"" : (w * (64 / a) + (n / a)) + "/" + 64 / a;
}
}
I'm trying to convert decimal to binary but some how when I convert 128 binary the output gives me 11111110, I tried to fix the calculation but still end up with the same output.
import java.lang.*;
public class HA7BinaryErr {
public static void main(String[] argv) {
Scanner input = new Scanner(System.in);
int number = 0;
int factorOfTwo = 0;
// get number to convert from user
do {
System.out.println("Enter the number to convert (0-255): ");
number = input.nextInt();
} while (number < 0 || number > 255);
System.out.println("The number " + number + " converted to binary is : ");
// convert to binary by successively dividing by larger factors of 2
for (factorOfTwo = 1; factorOfTwo <= 128; factorOfTwo *= 2) {
if (number / factorOfTwo >= 1) {
System.out.print("1");
number -= factorOfTwo;
} else
System.out.print("0");
}
} // end of main
}// end of class
You have a problem that you are writing the number backwards. You need to start with the highest bit first
for (int powerOfTwo = 128; powerOfTwo > 0; powerOfTwo /= 2) {
When you are writing in decimal you start with the highest power e.g. 1234 is 1 * 1000 + 2 * 100 + 3 * 10 + 4 * 1
You could take the easy way out and use:
Integer.toBinaryString(int i) then print the string to the console.
Check it out here.
public class DCTB {
public void convertor(int n)
{
for(int i=0;i<10;i++)
{
int arr=(int) (n%2);
n=n/2;
System.out.println(Integer.toString(arr));
}
}
public static void main(String args[])
{
DCTB obj=new DCTB();
obj.convertor(10);
}
}
Note: Updated on 06/17/2015. Of course this is possible. See the solution below.
Even if anyone copies and pastes this code, you still have a lot of cleanup to do. Also note that you will have problems inside the critical strip from Re(s) = 0 to Re(s) = 1 :). But this is a good start.
import java.util.Scanner;
public class NewTest{
public static void main(String[] args) {
RiemannZetaMain func = new RiemannZetaMain();
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 <= 0)
System.out.println("Value for the Zeta Function = " + riemannFuncForm(s));
else if (s == 1)
System.out.println("The zeta funxtion is undefined for Re(s) = 1.");
else if(s >= 2)
System.out.println("Value for the Zeta Function = " + getStandardSum(s));
else
System.out.println("Value for the Zeta Function = " + getNewSum(s));
stop = System.currentTimeMillis();
totalTime = (double) (stop-start) / 1000.0;
System.out.println("Total time taken is " + totalTime + " seconds.");
}
// Standard form the 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;
}
public static double getStandardSum(double s){
return standardZeta(s);
}
//New Form
// zeta(s) = 2^(-1+2 s)/((-2+2^s) Gamma(1+s)) integral_0^infinity t^s sech^2(t) dt for Re(s)>-1
public static double Integrate(double start, double end) {
double currentIntegralValue = 0;
double dx = 0.0001d; // The size of delta x in the approximation
double x = start; // A = starting point of integration, B = ending point of integration.
// Ending conditions for the while loop
// Condition #1: The value of b - x(i) is less than delta(x).
// This would throw an out of bounds exception.
// Condition #2: The value of b - x(i) is greater than 0 (Since you start at A and split the integral
// up into "infinitesimally small" chunks up until you reach delta(x)*n.
while (Math.abs(end - x) >= dx && (end - x) > 0) {
currentIntegralValue += function(x) * dx; // Use the (Riemann) rectangle sums at xi to compute width * height
x += dx; // Add these sums together
}
return currentIntegralValue;
}
private static double function(double s) {
double sech = 1 / Math.cosh(s); // Hyperbolic cosecant
double squared = Math.pow(sech, 2);
return ((Math.pow(s, 0.5)) * squared);
}
public static double getNewSum(double s){
double constant = Math.pow(2, (2*s)-1) / (((Math.pow(2, s)) -2)*(gamma(1+s)));
return constant*Integrate(0, 1000);
}
// Gamma Function - 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;
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;
}
//Binomial Co-efficient - NOT CURRENTLY USING
/*
public static double binomial(int n, int k)
{
if (k>n-k)
k=n-k;
long b=1;
for (int i=1, m=n; i<=k; i++, m--)
b=b*m/i;
return b;
} */
// Riemann's Functional Equation
// Tried this initially and utterly failed.
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);
double nextTerm = Math.pow(2, (1-s))*Math.pow(Math.PI, (1-s)-1)*(Math.sin((Math.PI*(1-s))/2))*gamma(1-(1-s));
double error = Math.abs(term - nextTerm);
if(s == 1.0)
return 0;
else
return Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s)*standardZeta(1-s);
}
}
Ok well we've figured out that for this particular function, since this form of it isn't actually a infinite series, we cannot approximate using recursion. However the infinite sum of the Riemann Zeta series (1\(n^s) where n = 1 to infinity) could be solved through this method.
Additionally this method could be used to find any infinite series' sum, product, or limit.
If you execute the code your currently have, you'll get infinite recursion as 1-(1-s) = s (e.g. 1-s = t, 1-t = s so you'll just switch back and forth between two values of s infinitely).
Below I talk about the sum of series. It appears you are calculating the product of the series instead. The concepts below should work for either.
Besides this, the Riemann Zeta Function is an infinite series. This means that it only has a limit, and will never reach a true sum (in finite time) and so you cannot get an exact answer through recursion.
However, if you introduce a "threshold" factor, you can get an approximation that is as good as you like. The sum will increase/decrease as each term is added. Once the sum stabilizes, you can quit out of recursion and return your approximate sum. "Stabilized" is defined using your threshold factor. Once the sum varies by an amount less than this threshold factor (which you have defined), your sum has stabilized.
A smaller threshold leads to a better approximation, but also longer computation time.
(Note: this method only works if your series converges, if it has a chance of not converging, you might also want to build in a maxSteps variable to cease execution if the series hasn't converged to your satisfaction after maxSteps steps of recursion.)
Here's an example implementation, note that you'll have to play with threshold and maxSteps to determine appropriate values:
/* Riemann's Functional Equation
* threshold - if two terms differ by less than this absolute amount, return
* currSteps/maxSteps - if currSteps becomes maxSteps, give up on convergence and return
* currVal - the current product, used to determine threshold case (start at 1)
*/
public static double riemannFuncForm(double s, double threshold, int currSteps, int maxSteps, double currVal) {
double nextVal = currVal*(Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s)); //currVal*term
if( s == 1.0)
return 0;
else if ( s == 0.0)
return -0.5;
else if (Math.abs(currVal-nextVal) < threshold) //When a term will change the current answer by less than threshold
return nextVal; //Could also do currVal here (shouldn't matter much as they differ by < threshold)
else if (currSteps == maxSteps)//When you've taken the max allowed steps
return nextVal; //You might want to print something here so you know you didn't converge
else //Otherwise just keep recursing
return riemannFuncForm(1-s, threshold, ++currSteps, maxSteps, nextVal);
}
}
This is not possible.
The functional form of the Riemann Zeta Function is --
zeta(s) = 2^s pi^(-1+s) Gamma(1-s) sin((pi s)/2) zeta(1-s)
This is different from the standard equation in which an infinite sum is measured from 1/k^s for all k = 1 to k = infinity. It is possible to write this as something similar to --
// Standard form the 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;
}
The same logic doesn't apply to the functional equation (it isn't a direct sum, it is a mathematical relationship). This would require a rather clever way of designing a program to calculate negative values of Zeta(s)!
The literal interpretation of this Java code is ---
// Riemann's Functional Equation
public static double riemannFuncForm(double s) {
double currentVal = (Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s));
if( s == 1.0)
return 0;
else if ( s == 0.0)
return -0.5;
else
System.out.println("Value of next value is " + nextVal(1-s));
return currentVal;//*nextVal(1-s);
}
public static double nextVal(double s)
{
return (Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s));
}
public static double getRiemannSum(double s) {
return riemannFuncForm(s);
}
Testing on three or four values shows that this doesn't work. If you write something similar to --
// Riemann's Functional Equation
public static double riemannFuncForm(double s) {
double currentVal = Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s); //currVal*term
if( s == 1.0)
return 0;
else if ( s == 0.0)
return -0.5;
else //Otherwise just keep recursing
return currentVal * nextVal(1-s);
}
public static double nextVal(double s)
{
return (Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s));
}
I was misinterpretation how to do this through mathematics. I will have to use a different approximation of the zeta function for values less than 2.
I think I need to use a different form of the zeta function. When I run the entire program ---
import java.util.Scanner;
public class Test4{
public static void main(String[] args) {
RiemannZetaMain func = new RiemannZetaMain();
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 >= 2)
System.out.println("Value for the Zeta Function = " + getStandardSum(s));
else
System.out.println("Value for the Zeta Function = " + getRiemannSum(s));
stop = System.currentTimeMillis();
totalTime = (double) (stop-start) / 1000.0;
System.out.println("Total time taken is " + totalTime + " seconds.");
}
// Standard form the 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;
}
public static double getStandardSum(double s){
return standardZeta(s);
}
// Riemann's Functional Equation
public static double riemannFuncForm(double s, double threshold, double currSteps, int maxSteps) {
double term = Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s);
//double nextTerm = Math.pow(2, (1-s))*Math.pow(Math.PI, (1-s)-1)*(Math.sin((Math.PI*(1-s))/2))*gamma(1-(1-s));
//double error = Math.abs(term - nextTerm);
if(s == 1.0)
return 0;
else if (s == 0.0)
return -0.5;
else if (term < threshold) {//The recursion will stop once the term is less than the threshold
System.out.println("The number of steps is " + currSteps);
return term;
}
else if (currSteps == maxSteps) {//The recursion will stop if you meet the max steps
System.out.println("The series did not converge.");
return term;
}
else //Otherwise just keep recursing
return term*riemannFuncForm(1-s, threshold, ++currSteps, maxSteps);
}
public static double getRiemannSum(double s) {
double threshold = 0.00001;
double currSteps = 1;
int maxSteps = 1000;
return riemannFuncForm(s, threshold, currSteps, maxSteps);
}
// Gamma Function - 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;
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;
}
//Binomial Co-efficient
public static double binomial(int n, int k)
{
if (k>n-k)
k=n-k;
long b=1;
for (int i=1, m=n; i<=k; i++, m--)
b=b*m/i;
return b;
}
}
I notice that plugging in zeta(-1) returns -
Enter the value of s inside the Riemann Zeta Function: -1
The number of steps is 1.0
Value for the Zeta Function = -0.0506605918211689
Total time taken is 0.0 seconds.
I knew that this value was -1/12. I checked some other values with wolfram alpha and observed that --
double term = Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s);
Returns the correct value. It is just that I am multiplying this value every time by zeta(1-s). In the case of Zeta(1/2), this will always multiply the result by 0.99999999.
Enter the value of s inside the Riemann Zeta Function: 0.5
The series did not converge.
Value for the Zeta Function = 0.999999999999889
Total time taken is 0.006 seconds.
I am going to see if I can replace the part for --
else if (term < threshold) {//The recursion will stop once the term is less than the threshold
System.out.println("The number of steps is " + currSteps);
return term;
}
This difference is the error between two terms in the summation. I may not be thinking about this correctly, it is 1:16am right now. Let me see if I can think better tomorrow ....
With the help of some very nice people from this forum I've been able to translate some c++ into java language, but I'm not sure how to call this classes. Bassically what they are supposed to do is to return a "gen4 style" curve. If someone have an idea how to get this running please let me know!
/*
Derived from gen4 from the UCSD Carl package, described in F.R. Moore,
"Elements of Computer Music." It works like setline, but there's an
additional argument for each time,value pair (except the last). This
arg determines the curvature of the segment, and is called "alpha" in
the comments to trans() below. -JGG, 12/2/01
http://www.music.columbia.edu/cmc/rtcmix/docs/docs.html (maketable/gen4)
trans(a, alpha, b, n, output) makes a transition from <a> to <b> in
<n> steps, according to transition parameter <alpha>. It stores the
resulting <n> values starting at location <output>.
alpha = 0 yields a straight line,
alpha < 0 yields an exponential transition, and
alpha > 0 yields a logarithmic transition.
All of this in accord with the formula:
output[i] = a + (b - a) * (1 - exp(i * alpha / (n-1))) / (1 - exp(alpha))
for 0 <= i < n
*/
import java.lang.Math;
private static final int MAX_POINTS =1024;
public class gen{
int size; /* size of array to load up */
int nargs; /* number of arguments passed in p array */
float []pvals; /* address of array of p values */
double []array; /* address of array to be loaded up */
int slot; /* slot number, for fnscl test */
}
public static void fnscl(gen g) {
}
static void trans(double a, double alpha, double b, int n, double[] output) {
double delta = b - a;
if (output.length <= 1) {
output[0] = a;
return;
}
double interval = 1.0 / (output.length - 1);
if (alpha != 0) {
double denom = 1 / (1 - Math.exp(alpha));
for (int i = 0; i < output.length; i++)
output[i] = a + (1 - Math.exp(i * alpha * interval)) * delta * denom;
} else {
for (int i = 0; i < output.length; i++)
output[i] = a + i * delta * interval;
}
}
public static double gen4(gen g) {
int i;
int points = 0;
int seglen = 0;
double factor;
double time [] = new double[MAX_POINTS];
double value [] = new double[MAX_POINTS];
double alpha [] = new double[MAX_POINTS];
double ptr [];
if (g.nargs < 5 || (g.nargs % 3) != 2) /* check number of args */
System.out.println("gen4 usage: t1 v1 a1 ... tn vn");
if ((g.nargs / 3) + 1 > MAX_POINTS)
System.out.println("gen4 too many arguments");
for (i = points = 0; i < g.nargs; points++) {
time[points] = g.pvals[i++];
if (points > 0 && time[points] < time[points - 1])
System.out.println("gen4 non-increasing time values");
value[points] = g.pvals[i++];
if (i < g.nargs)
alpha[points] = g.pvals[i++];
}
factor = (g.size - 1) / time[points - 1];
for (i = 0; i < points; i++)
time[i] *= factor;
ptr = g.array;
for (i = 0; i < points - 1; i++) {
seglen = (int) (Math.floor(time[i + 1] + 0.5)
- Math.floor(time[i] + 0.5) + 1);
trans(value[i], alpha[i], value[i + 1], seglen, ptr);
ptr[i] += seglen - 1;
}
fnscl(g);
return 0.0;
}
If I understand your question correctly and you want to execute your program, you need some adjustments to your code.
You need to have a class. To execute it, you need a special main method.
/**
*Derived from...
*/
import java.lang.Math;
class Gen4Func {
class Gen {
// insert from question
}
public static void main(String[] args) {
// prepare parameters
// ...
// call your function
trans( ... );
// do more stuff
// ...
}
public static void fnscl(gen g) {
}
static void trans(double a, double alpha, double b, int n, double[] output) {
// insert from above
}
}
Save this to Gen4Func.java (must match class name). Then execute from via
> java Gen4Func
As I said: If I understand your question correctly.
HTH,
Mike
Bulky, copypaste to Gen.java and try setting Gen class fields with test values in main() method.
/*
* Derived from gen4 from the UCSD Carl package, described in F.R. Moore,
* "Elements of Computer Music." It works like setline, but there's an additional
* argument for each time,value pair (except the last). This arg determines the
* curvature of the segment, and is called "alpha" in the comments to trans()
* below. -JGG, 12/2/01
*
* http://www.music.columbia.edu/cmc/rtcmix/docs/docs.html (maketable/gen4)
*
*
*
* trans(a, alpha, b, n, output) makes a transition from <a> to <b> in <n>
* steps, according to transition parameter <alpha>. It stores the resulting <n>
* values starting at location <output>. alpha = 0 yields a straight line, alpha
* < 0 yields an exponential transition, and alpha > 0 yields a logarithmic
* transition. All of this in accord with the formula: output[i] = a + (b - a) *
* (1 - exp(i * alpha / (n-1))) / (1 - exp(alpha)) for 0 <= i < n
*/
public class Gen {
private static final int MAX_POINTS = 1024;
int size; //size of array to load up
int nargs; //number of arguments passed in p array
float[] pvals; //address of array of p values
double[] array; //address of array to be loaded up
int slot; //slot number, for fnscl test
public static void main(String[] args) {
Gen g = new Gen();
//initialize Gen fields here..
Gen.gen4(g);
}
public static void fnscl(Gen g) {
}
public static void trans(double a, double alpha, double b, int n, double[] output) {
double delta = b - a;
if (output.length <= 1) {
output[0] = a;
return;
}
double interval = 1.0 / (output.length - 1);
if (alpha != 0) {
double denom = 1 / (1 - Math.exp(alpha));
for (int i = 0; i < output.length; i++) {
output[i] = a + (1 - Math.exp(i * alpha * interval)) * delta * denom;
}
} else {
for (int i = 0; i < output.length; i++) {
output[i] = a + i * delta * interval;
}
}
}
public static double gen4(Gen g) {
int i;
int points = 0;
int seglen = 0;
double factor;
double time[] = new double[MAX_POINTS];
double value[] = new double[MAX_POINTS];
double alpha[] = new double[MAX_POINTS];
double ptr[];
if (g.nargs < 5 || (g.nargs % 3) != 2) /*
* check number of args
*/ {
System.out.println("gen4 usage: t1 v1 a1 ... tn vn");
}
if ((g.nargs / 3) + 1 > MAX_POINTS) {
System.out.println("gen4 too many arguments");
}
for (i = points = 0; i < g.nargs; points++) {
time[points] = g.pvals[i++];
if (points > 0 && time[points] < time[points - 1]) {
System.out.println("gen4 non-increasing time values");
}
value[points] = g.pvals[i++];
if (i < g.nargs) {
alpha[points] = g.pvals[i++];
}
}
factor = (g.size - 1) / time[points - 1];
for (i = 0; i < points; i++) {
time[i] *= factor;
}
ptr = g.array;
for (i = 0; i < points - 1; i++) {
seglen = (int) (Math.floor(time[i + 1] + 0.5)
- Math.floor(time[i] + 0.5) + 1);
trans(value[i], alpha[i], value[i + 1], seglen, ptr);
ptr[i] += seglen - 1;
}
fnscl(g);
return 0.0;
}
}
In Java, stand alone methods are not allowed. You should make them member of some class. In your case, it seems that 2 of your methods are using class gen as argument fnscl() amd gen4(). You can make them as member methods. The other one can remain static within class.
public class gen{
// data ...
public void fnscl () { ... } // member method
public double gen4 () { ... } // member method
// static method
public static void trans(double a, double alpha, double b, int n, double[] output) { ... }
}
main() also should be part of some class. I leave that choice up to you.
Java is a fully object oriented language in terms of paradigms. (Not as c++ which is also procedural), that's why as Kerrek SB said all methods has to be declared and defined inside a class.
What he was mistaken is that a file can contain only one public class and it has to be named exactly as the file. But it can also contain any number non-public classes with arbitrary names.
To run the program, you have to first compile the file with javac [filename].java then run it with java [classname] without! .class
One more thing. You can't declare a method like this:
public void foo();
The compiler will consider it to be an abstract method and raise an error message.
Is there any other way in Java to calculate a power of an integer?
I use Math.pow(a, b) now, but it returns a double, and that is usually a lot of work, and looks less clean when you just want to use ints (a power will then also always result in an int).
Is there something as simple as a**b like in Python?
When it's power of 2. Take in mind, that you can use simple and fast shift expression 1 << exponent
example:
22 = 1 << 2 = (int) Math.pow(2, 2)
210 = 1 << 10 = (int) Math.pow(2, 10)
For larger exponents (over 31) use long instead
232 = 1L << 32 = (long) Math.pow(2, 32)
btw. in Kotlin you have shl instead of << so
(java) 1L << 32 = 1L shl 32 (kotlin)
Integers are only 32 bits. This means that its max value is 2^31 -1. As you see, for very small numbers, you quickly have a result which can't be represented by an integer anymore. That's why Math.pow uses double.
If you want arbitrary integer precision, use BigInteger.pow. But it's of course less efficient.
Best the algorithm is based on the recursive power definition of a^b.
long pow (long a, int b)
{
if ( b == 0) return 1;
if ( b == 1) return a;
if (isEven( b )) return pow ( a * a, b/2); //even a=(a^2)^b/2
else return a * pow ( a * a, b/2); //odd a=a*(a^2)^b/2
}
Running time of the operation is O(logb).
Reference:More information
No, there is not something as short as a**b
Here is a simple loop, if you want to avoid doubles:
long result = 1;
for (int i = 1; i <= b; i++) {
result *= a;
}
If you want to use pow and convert the result in to integer, cast the result as follows:
int result = (int)Math.pow(a, b);
Google Guava has math utilities for integers.
IntMath
import java.util.*;
public class Power {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int num = 0;
int pow = 0;
int power = 0;
System.out.print("Enter number: ");
num = sc.nextInt();
System.out.print("Enter power: ");
pow = sc.nextInt();
System.out.print(power(num,pow));
}
public static int power(int a, int b)
{
int power = 1;
for(int c = 0; c < b; c++)
power *= a;
return power;
}
}
Guava's math libraries offer two methods that are useful when calculating exact integer powers:
pow(int b, int k) calculates b to the kth the power, and wraps on overflow
checkedPow(int b, int k) is identical except that it throws ArithmeticException on overflow
Personally checkedPow() meets most of my needs for integer exponentiation and is cleaner and safter than using the double versions and rounding, etc. In almost all the places I want a power function, overflow is an error (or impossible, but I want to be told if the impossible ever becomes possible).
If you want get a long result, you can just use the corresponding LongMath methods and pass int arguments.
Well you can simply use Math.pow(a,b) as you have used earlier and just convert its value by using (int) before it. Below could be used as an example to it.
int x = (int) Math.pow(a,b);
where a and b could be double or int values as you want.
This will simply convert its output to an integer value as you required.
A simple (no checks for overflow or for validity of arguments) implementation for the repeated-squaring algorithm for computing the power:
/** Compute a**p, assume result fits in a 32-bit signed integer */
int pow(int a, int p)
{
int res = 1;
int i1 = 31 - Integer.numberOfLeadingZeros(p); // highest bit index
for (int i = i1; i >= 0; --i) {
res *= res;
if ((p & (1<<i)) > 0)
res *= a;
}
return res;
}
The time complexity is logarithmic to exponent p (i.e. linear to the number of bits required to represent p).
I managed to modify(boundaries, even check, negative nums check) Qx__ answer. Use at your own risk. 0^-1, 0^-2 etc.. returns 0.
private static int pow(int x, int n) {
if (n == 0)
return 1;
if (n == 1)
return x;
if (n < 0) { // always 1^xx = 1 && 2^-1 (=0.5 --> ~ 1 )
if (x == 1 || (x == 2 && n == -1))
return 1;
else
return 0;
}
if ((n & 1) == 0) { //is even
long num = pow(x * x, n / 2);
if (num > Integer.MAX_VALUE) //check bounds
return Integer.MAX_VALUE;
return (int) num;
} else {
long num = x * pow(x * x, n / 2);
if (num > Integer.MAX_VALUE) //check bounds
return Integer.MAX_VALUE;
return (int) num;
}
}
base is the number that you want to power up, n is the power, we return 1 if n is 0, and we return the base if the n is 1, if the conditions are not met, we use the formula base*(powerN(base,n-1)) eg: 2 raised to to using this formula is : 2(base)*2(powerN(base,n-1)).
public int power(int base, int n){
return n == 0 ? 1 : (n == 1 ? base : base*(power(base,n-1)));
}
There some issues with pow method:
We can replace (y & 1) == 0; with y % 2 == 0
bitwise operations always are faster.
Your code always decrements y and performs extra multiplication, including the cases when y is even. It's better to put this part into else clause.
public static long pow(long x, int y) {
long result = 1;
while (y > 0) {
if ((y & 1) == 0) {
x *= x;
y >>>= 1;
} else {
result *= x;
y--;
}
}
return result;
}
Use the below logic to calculate the n power of a.
Normally if we want to calculate n power of a. We will multiply 'a' by n number of times.Time complexity of this approach will be O(n)
Split the power n by 2, calculate Exponentattion = multiply 'a' till n/2 only. Double the value. Now the Time Complexity is reduced to O(n/2).
public int calculatePower1(int a, int b) {
if (b == 0) {
return 1;
}
int val = (b % 2 == 0) ? (b / 2) : (b - 1) / 2;
int temp = 1;
for (int i = 1; i <= val; i++) {
temp *= a;
}
if (b % 2 == 0) {
return temp * temp;
} else {
return a * temp * temp;
}
}
Apache has ArithmeticUtils.pow(int k, int e).
import java.util.Scanner;
class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
try {
long x = sc.nextLong();
System.out.println(x + " can be fitted in:");
if (x >= -128 && x <= 127) {
System.out.println("* byte");
}
if (x >= -32768 && x <= 32767) {
//Complete the code
System.out.println("* short");
System.out.println("* int");
System.out.println("* long");
} else if (x >= -Math.pow(2, 31) && x <= Math.pow(2, 31) - 1) {
System.out.println("* int");
System.out.println("* long");
} else {
System.out.println("* long");
}
} catch (Exception e) {
System.out.println(sc.next() + " can't be fitted anywhere.");
}
}
}
}
int arguments are acceptable when there is a double paramter. So Math.pow(a,b) will work for int arguments. It returns double you just need to cast to int.
int i = (int) Math.pow(3,10);
Without using pow function and +ve and -ve pow values.
public class PowFunction {
public static void main(String[] args) {
int x = 5;
int y = -3;
System.out.println( x + " raised to the power of " + y + " is " + Math.pow(x,y));
float temp =1;
if(y>0){
for(;y>0;y--){
temp = temp*x;
}
} else {
for(;y<0;y++){
temp = temp*x;
}
temp = 1/temp;
}
System.out.println("power value without using pow method. :: "+temp);
}
}
Unlike Python (where powers can be calculated by a**b) , JAVA has no such shortcut way of accomplishing the result of the power of two numbers.
Java has function named pow in the Math class, which returns a Double value
double pow(double base, double exponent)
But you can also calculate powers of integer using the same function. In the following program I did the same and finally I am converting the result into an integer (typecasting). Follow the example:
import java.util.*;
import java.lang.*; // CONTAINS THE Math library
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n= sc.nextInt(); // Accept integer n
int m = sc.nextInt(); // Accept integer m
int ans = (int) Math.pow(n,m); // Calculates n ^ m
System.out.println(ans); // prints answers
}
}
Alternatively,
The java.math.BigInteger.pow(int exponent) returns a BigInteger whose value is (this^exponent). The exponent is an integer rather than a BigInteger. Example:
import java.math.*;
public class BigIntegerDemo {
public static void main(String[] args) {
BigInteger bi1, bi2; // create 2 BigInteger objects
int exponent = 2; // create and assign value to exponent
// assign value to bi1
bi1 = new BigInteger("6");
// perform pow operation on bi1 using exponent
bi2 = bi1.pow(exponent);
String str = "Result is " + bi1 + "^" +exponent+ " = " +bi2;
// print bi2 value
System.out.println( str );
}
}