Related
Question:
A class SeriesSum is designed to calculate the sum of the following series:
Class name : SeriesSum
Data members/instance variables:
x : to store an integer number
n : to store number of terms
sum : double variable to store the sum of the series
Member functions:
SeriesSum(int xx, int nn) : constructor to assign x=xx and n=nn
double findfact(int m) to return the factorial of m using recursive
technique.
double findpower(int x, int y) : to return x raised to the power of y using
recursive technique.
void calculate( ) : to calculate the sum of the series by invoking
the recursive functions respectively
void display( ) : to display the sum of the series
(a) Specify the class SeriesSum, giving details of the constructor(int, int),
double findfact(int), double findpower(int, int), void calculate( ) and
void display( ).
Define the main( ) function to create an object and call the
functions accordingly to enable the task.
Code:
class SeriesSum
{
int x,n;
double sum;
SeriesSum(int xx,int nn)
{ x=xx;
n=nn;
sum=0.0;
}
double findfact(int a)
{ return (a<2)? 1:a*findfact(a-1);
}
double findpower(int a, int b)
{ return (b==0)? 1:a*findpower(a,b-1);
}
void calculate()
{ for(int i=2;i<=n;i+=2)
sum += findpower(x,i)/findfact(i-1);
}
void display()
{ System.out.println("sum="+ sum);
}
static void main()
{ SeriesSum obj = new SeriesSum(3,8);
obj.calculate();
obj.display();
}
}
MyProblem:
I am having problems in understanding that when i= any odd number (Taking an example such as 3 here)then it value that passes through findfact is (i-1)=2 then how am I getting the odd factorials such as 3!
Any help or guidance would be highly appreciated.
Optional:
If you can somehow explain the recursion taking place in the findpower and findfactorial,it would be of great help.
Take a closer look a the loop. i starts at 2 and is incremented by 2 every iteration, so it is never odd. It corresponds to the successive powers of x, each of which is divided by the factorial of i -1 (which IS odd).
As for the recursion in findfact, you just need to unwrap the first few calls by hand to see why it works :
findfact(a) = a * findfact(a -1)
= a * (a - 1) * findfact(a -2)
= a * (a - 1) * (a - 2) * findfact(a - 3)
...
= a * (a - 1) * (a - 2) * ... * 2 * findfact(1)
= a * (a - 1) * (a - 2) * ... * 2 * 1
= a!*
The same reasoning works with findpower.
As a side note, while it may be helpful for teaching purposes, recursion is a terrible idea for computing factorials or powers.
I'm not sure I understand your question correctly, but I try to help you the best I can.
I am having problems in understanding that when i= any odd number
In this code i never will be any odd number
for(int i=2;i<=n;i+=2)
i will be: 2 , 4 , 6 , 8 and so on because i+=2
The Recursion
The findfact() function in a more readable version:
double findfact(int a){
if(a < 2 ){
return 1;
} else {
return a * findfact(a - 1);
}
}
you can imagine it as a staircase, every call of findfact is a step:
We test: if a < 2 then return 1 else we call findfact() again with a-1 and multiply a with the result of findfact()
The same function without recursion:
double findfact(int a){
int sum = 1;
for(int i = a; i > 0; i--){
sum *= i;
}
return sum;
}
Same by the findpower function:
if b == 0 then return 1 else call findpower() with a, b-1 and multiply the return value of findpower() with a
So the last called findpower() will return 1 (b = 0)
The second last findpower() will return a * 1 (b = 1)
The third last findpower() will return a * a * 1 (b = 2)
so you can see findpower(a, 2) = a * a * 1 = a^2
Hope I could help you
Try to run below code, it will clear all your doubts (i have modified some access specifier and created main method)
public class SeriesSum
{
int x,n;
double sum;
SeriesSum(int xx,int nn)
{ x=xx;
n=nn;
sum=0.0;
}
double findfact(int a)
{ return (a<2)? 1:a*findfact(a-1);
}
double findpower(int a, int b)
{ return (b==0)? 1:a*findpower(a,b-1);
}
void calculate()
{
System.out.println("x ="+x);
System.out.println("n ="+n);
for(int i=2;i<=n;i+=2){
System.out.println(x+"^"+i+"/"+(i-1)+"!" +" = " +(findpower(x,i)+"/"+findfact(i-1)) );
//System.out.println(findpower(x,i)+"/"+findfact(i-1));
sum += findpower(x,i)/findfact(i-1);
}
}
void display()
{ System.out.println("sum="+ sum);
}
public static void main(String arg[])
{ SeriesSum obj = new SeriesSum(3,8);
obj.calculate();
obj.display();
}
}
// ----- output ----
x =3
n =8
3^2/1! = 9.0/1.0
3^4/3! = 81.0/6.0
3^6/5! = 729.0/120.0
3^8/7! = 6561.0/5040.0
sum=29.876785714285713
You can simplify the summation and get rid of power and factorial. Please notice:
The very first term is just x * x
If you know term item == x ** (2 * n) / (2 * n - 1)! the next one will be item * x * x / (2 * n) / (2 * n + 1).
Implementation:
private static double sum(double x, int count) {
double item = x * x; // First item
double result = item;
for (int i = 1; i <= count; ++i) {
// Next item from previous
item = item * x * x / (2 * i) / (2 * i +1);
result += item;
}
return result;
}
In the real world, you can notice that
sinh(x) = x/1! + x**3/3! + x**5/5! + ... + x**(2*n - 1) / (2*n - 1)! + ...
and your serie is nothing but
x * sinh(x) = x**2/1! + x**4 / 3! + ... + x**(2*n) / (2*n - 1)! + ...
So you can implement
private static double sum(double x) {
return x * (Math.exp(x) - Math.exp(-x)) / 2.0;
}
My objective is to provide a class Stacker that contains a method stackSize that takes an int called extension as its parameter. It should return the smallest long n such that the sum of the sequence 1/2 + 1/4 + 1/6 + 1/8 + ... + ... + 1/2n is greater than or equal to extension.
Assuming my Rat class (Rational Number) correctly adds up two fractions using the first parameter as a numerator and the second parameter as a denominator, any ideas why this code isn't working for me?
The default Rat() constructor simply makes the Rational number (0/1) and the Rat(extension) constructor makes the Rational number (extension/1).
public class StackerTest {
#Test
public void test1()
{
assertEquals(4, Stacker.stackSize(1));
}
}
When I run the test case:
#Test
public void test1()
{
assertEquals(4, Stacker.stackSize(1));
}
It runs for a solid 30 seconds before giving an IllegalArgumentException
Here is the constructor for Rat class as well as the add method
/**
* If d is zero, throws an IllegalArgumentException. Otherwise creates the
* rational number n/d
*/
public Rat (int n, int d)
{
// Check parameter restriction
if (d == 0)
{
throw new IllegalArgumentException();
}
// Adjust sign of denominator
num = n;
den = d;
if (den < 0)
{
num = -num;
den = -den;
}
// Zero has a standard representation
if (num == 0)
{
den = 1;
}
// Factor out common terms
int g = gcd(Math.abs(num), den);
num = num / g;
den = den / g;
}
/**
* Returns the sum of this and r
*/
public Rat add (Rat r)
{
int firstNum = this.num*r.den;
int firstDen = this.den*r.den;
int secondNum = r.num*this.den;
int secondDen = r.den*this.den;
Rat x = new Rat(firstNum+secondNum, firstDen);
return x;
}
so I need to figure out this problem for a class. How would you do it?
Given three ints, a b c, one of them is small, one is medium and
one is large. Print true if the three values are evenly spaced,
so the difference between small and medium is the same as the
difference between medium and large.
(2, 4, 6) -> true
(4, 6, 2) -> true
(4, 6, 3) -> false
There is no need for any sorting, with such a small number of inputs.
Since there are only three possibilities, you can just check each of them individually, and "or" the results.
boolean isArithmeticProgression =
(a - b == b - c) || (a - c == c - b) || (a - b == c - a)
Although David Wallace mentions that you should just subtract the values because you have such a small set of numbers -- if you have hundreds of numbers, the following works for any size.
import java.util.*;
public class EvenSpaces {
public static void main(String[] args) {
int[][] data = {
{ 2, 4, 6 }, //-> true
{ 4, 6, 2 }, //-> true
{ 4, 6, 3 } //-> false
};
for (int[] d: data) {
System.out.printf("%s - %s%n", toList(d), areEvenlySpaced(toList(d)));
}
}
public static boolean areEvenlySpaced(List<Integer> list) {
Collections.sort(list, new Comparator<Integer>() {
public int compare(Integer i1, Integer i2) {
return i2.compareTo(i1);
}
});
if (list != null && list.size() > 1) {
int lastDiff = list.get(0) - list.get(1);
for (int i = 1; i < list.size(); i++) {
int diff = Math.abs(list.get(i-1) - list.get(i));
if (lastDiff != diff) return false;
lastDiff = diff;
}
return true;
}
return false;
}
public static List<Integer> toList(int[] values) {
List<Integer> list = new ArrayList<Integer>(values.length);
for (int n : values) list.add(n);
return list;
}
}
One thing you can do is calculate small, medium and large so the order of your ints won't matter anymore.
Then, you can simply check if the difference between large and medium is the same as medium and small, returning true or false accordingly.
Below is a smple code:
static boolean spacedEvenly(int a, int b, int c) {
int large = Math.max(a, Math.max(b, c));
int small = Math.min(a, Math.min(b, c));
int medium = (a + b + c) - (large + small);
return ((large - medium) == (medium - small));
}
Since your array seems to be a small array, why not try linear traversal ? So as you traverse the array of size (n-1), take the abs(diff) of the 2 elements, then take the abs(diff) of 2 more etc. if diff happens to be the same, return true else false. all this is happening in a loop...
time O(n)
PS: I am not suggesting sorting as your requirement is just to see if the diff between 2 elements is constant. sorting is unnecessary.
This method should do the trick:
public boolean areEvenlySpaced(int a, int b, int c) {
Integer[] ints = {a, b, c};
Arrays.sort(ints, new Comparator<Integer>()
{
#Override
public int compare(Integer x, Integer y)
{
return x - y;
}
});
if ((ints[0]-ints[1]) == (ints[1]-ints[2])) return true;
else return false;
}
public boolean evenlySpaced(int a, int b, int c) {
int[] jawn = {a, b, c};
java.util.Arrays.sort(jawn);
if(a == b) {
if(b == c) return true;
}
if(Math.abs(jawn[0] - jawn[1]) == Math.abs(jawn[1] - jawn[2])) return true;
return false;
}
boolean method (int a, int b, int c)
{
return ( a*3==a+b+c || b*3==a+b+c || c*3==a+b+c );
}
// if spaces are even, one of given ints is an average of their sum.
Try the following code:
int temp;
if(a > b) {
temp = a;
a = b;
b = temp;
}
if(b > c) {
temp = b;
b = c;
c = temp;
}
if(a > b) {
temp = a;
a = b;
b = temp;
}
return b - a == c - b;
if(a==b&&b!=c||a==c&&c!=b||b==c&&c!=a){
return false;
}
return a-b==b-c||b-c==c-a||c-a==a-b;
}
This should work for you.
public boolean evenlySpaced(int a, int b, int c) {
int small = Math.min(a,b);
small = Math.min(small,c);
int large = Math.max(a,b);
large = Math.max(large,c);
int medium = (small + large)/2;
boolean flag = false;
if(a == medium || b == medium || c == medium)
flag = true;
return ((large - medium) == (medium - small) && flag);
}
/*
3. Create a method spacedEvenly thats given three ints, a b c, one of them
is small, one is medium and one is large. Print true if the three values are
evenly spaced. So the difference from small to medium is the same as the
difference between medium and large.
spacedEvenly(2, 4, 6) → true
spacedEvenly(-1, 0, 1) → True
spacedEvenly(6, 1, 7) → false */
package javaexam3;
import java.util.Scanner;
public class JavaExam3 {
public static String spacedEvenly(String n) {
Scanner input = new Scanner(System.in);
n = "";
System.out.print("What is the first integer declared as variable a?: ");
int a = input.nextInt();
System.out.print("What is the second integer declared as variable b?:");
int b = input.nextInt();
System.out.print("What is the third integer declared as variable c?: ");
int c = input.nextInt();
if( ((b - a) + b == c) && ((c - b) + a == b))
{
n = " True";
}
else {
n = " False";
}
System.out.println("\nOkay! Are " + a + "," + b + "," + c + " evenly
spaced? " + n + "\n\n");
return n;
}
public static void main(String[] args) {
//Scanner input = new Scanner(System.in);
String n = "nothing";
System.out.print("Web Development Fundamentals\n\n ");
System.out.print("OK, Give me three integers 'a, b, and c'.\nIf they are
evenly spaced I will tell you, "
+ "if in fact, it is true.\nIf the intgers are not even spaced,"
+ "I will declare the statement to be false! \n\nGOT IT?\n\t"
+ "OKAY ...LETS BEGIN.\n\n");
spacedEvenly(n);
}
}
public boolean evenlySpaced(int a, int b, int c) {
int max = Math.max(a, Math.max(b,c));
int min = Math.min(a, Math.min(b,c));
int mid = (a+b+c) - max - min;
return max - mid == mid - min;
}
Solving a quadratic equation
I have the following written down so far. I am not sure on how to introduce the second method
public static void main(string args[]){
}
public static double quadraticEquationRoot1(int a, int b, int c) (){
}
if(Math.sqrt(Math.pow(b, 2) - 4*a*c) == 0)
{
return -b/(2*a);
} else {
int root1, root2;
root1 = (-b + Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a);
root2 = (-b - Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a);
return Math.max(root1, root2);
}
}
Firstly, your code won't compile--you have an extra } after the start of public static double quadraticEquationRoot1(int a, int b, int c) ().
Secondly, you aren't looking for the correct input types. If you want input of type double, make sure you declare the method appropriately. Also be careful of declaring things as int when they could be doubles (for example, root1 and root2).
Thirdly, I don't know why you have the if/else block--it would be better to simply skip it, and only use the code that is currently in the else part.
Finally, to address your original question: Simply create a separate method and use Math.min() instead of Math.max().
So, to recap in code:
public static void main(string args[]){
}
//Note that the inputs are now declared as doubles.
public static double quadraticEquationRoot1(double a, double b, double c) (){
double root1, root2; //This is now a double, too.
root1 = (-b + Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a);
root2 = (-b - Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a);
return Math.max(root1, root2);
}
public static double quadraticEquationRoot2(double a, double b, double c) (){
//Basically the same as the other method, but use Math.min() instead!
}
Well why don't you try to use the same exact algorithms but then use Math.min in your return statement?
Also, note that you're not taking into account whether or not $b$ is negative in your first if statement. In other words you simply return $-b / 2a$ but you don't check if $b$ is negative, if it isn't then this is actually the smaller of the two roots not the larger.
Sorry about that! I misinterpreted what was going on xD
package QuadraticEquation;
import javax.swing.*;
public class QuadraticEquation {
public static void main(String[] args) {
String a = JOptionPane.showInputDialog(" Enter operand a : ");
double aa = Double.parseDouble(a);
String b = JOptionPane.showInputDialog(" Enter operand b : ");
double bb = Double.parseDouble(b);
String c = JOptionPane.showInputDialog(" Enter operand c : ");
double cc = Double.parseDouble(c);
double temp = Math.sqrt(bb * bb - 4 * aa * cc);
double r1 = ( -bb + temp) / (2*aa);
double r2 = ( -bb -temp) / (2*aa);
if (temp > 0) {
JOptionPane.showMessageDialog(null, "the equation has two real roots" +"\n"+" the roots are : "+ r1+" and " +r2);
}
else if(temp ==0) {
JOptionPane.showMessageDialog(null, "the equation has one root"+ "\n"+ " The root is : " +(-bb /2 * aa));
}
else{
JOptionPane.showMessageDialog(null, "the equation has no real roots !!!");
}
}
}
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.