Well, I am doing a practice problem (preparing for midterm) and I was able to get one of the outputs correct. However, I am having troublesome getting the average input. It ends up at 12.0 instead of 6.5
Here's the prompt question:5.
Complete the following Java program by filling in the bodies of functions sum(), avg(), and ord(). A call to sum(n) should return the sum of all the integers from 1 to n, while avg(n) returns the average of the same set of numbers. A call to the boolean function ord(x, y, z) returns true if x < y< z and false otherwise. The Function main() should produce the following output
Output:
6.5 true false
This is my code:
class Problem5 {
// sum(): return 1+2+3+..+n
static int sum(int n) { //this is given
int sum = 0;
for(int i=0; i<n; i++) {
sum += n;
}
return n;
}
// avg(): return average of {1,2,..,n}
static double avg(int n) { // given
double sum = 0;
for (int i=1; i<n; i++) {
sum +=n;
}
return sum / n;
}
//ord(): return true if and only if x<y<z
static boolean ord(double x, double y, double z){ //given
if (x < y && y <z){
return true;
} else {
return false;
}
}
public static void main (String[]args) {
System.out.println(avg(12));
System.out.println(ord(1.2,3.4,5.6));
System.out.println(ord(3.4,1.2,5.6));
}
}
Overall I am having trouble coding/ filling in the code for static int sum(int) and static double avg(int).
This:
for (int i=1; i<n; i++){
Will skip n. (it will loop on 1...n-1). For 12, the sum will be 11*12/2, which you then divide by 12, resulting in 11/2 = 6.5
Fix it like so:
for (int i = 1; i <= n; i++) {
(or replace the whole loop by return (double) (n+1) / 2.0)
For your sum function, there is the same error, plus the return value is not good:
return n;
Should be
return sum;
And the increment should be sum += i;, not n (you want 1+2+3+4..., not 12+12+12+12...)
Again, you can replace the whole loop by return n * (n + 1) / 2
I assume your teacher would expect you to learn about re usability, and since your 2 loops in sum and in avg are identical, you could write:
public static double avg(int n) {
return (double) sum(n) / n;
}
A sum is just the addition of all the numbers in a certain range:
static int sum(int n) {
int total = 0;
for(int i = 1; i <= n; i++) {
total += i;
}
return total;
}
Average is just the sum of the range divided by the amount of numbers:
static double avg(int n) {
return sum(n) / (double) n;
}
Related
I am having problems with summing up the products produced from my java loop.
public class ArtificialNeuron {
public ArtificialNeuron(double[] weightings) {
weights = weightings;
inputs = new double[6];
inputs[0] = 1;
}
public void setInput(int index, double newValue) {
inputs[index] = newValue;
}
public int activate(double threshold) {
double x = 0;
for(int i=0; i<inputs.length;i++)
x = inputs[i]*weights[i];
double sum = x+x+x+x+x+x;
if(sum >= threshold) {
return 1;
} else {
return -1;
}
}
}
I ran several Junit test and it always seem to fail on the if else statement. I believe it probably my summation method, but I don't know how I would sum up the products.
Based on your code, I think you wanted to add all of the products together. Instead, you are multiplying the last product by 6 (effectively). It's unclear why you have the temporary x, you can add each product to a default sum of 0. Also, I think a test for sum < threshold is a little easier to read (likewise, always use braces with your loops - it's easier to read and reason about). Like,
public int activate(double threshold) {
double sum = 0;
for (int i = 0; i < inputs.length; i++) {
sum += inputs[i] * weights[i]; // sum = sum + (inputs[i] * weights[i])
}
if (sum < threshold) {
return -1;
}
return 1;
}
What will be the algorithm for calculating the given series?
Series to be calculated
Here's what I coded till now:
public static double sumOfSeries(double x, int numTerms) { // -1 <= x <= 1
double sum = x;
for(int i = 1; i <= numTerms; i++) {
}
return sum;
}
try to separate the coefficients from polynomials and calculate those in separate methods. Example:
public class NewClass {
public static void main(String[] args) {
int greatestExponent = 9;
double x = 0.5;
System.out.println(calculate(x,greatestExponent));
}
public static double getCoefficient(int n){
double coff = 1;
for(int i=1; i<n; i++){
if(i%2==0){
coff = coff/i; //if even put it in the denominator
}
else{
coff = coff*i; // else numerator
}
}
return coff/n; // at the end divide with the exponent (ex. x^9 /9)
}
public static double calculate(double x, int expo){
double result = 1;
for (int i = 1; i<= expo; i+=2){
result += (getCoefficient(i)*Math.pow(x, i)); //for each odd exponent calculate the cofficient and x^i
}
return result;
}
}
Necessary to find all regularity in proposed equation.
x -> x^3 -> x^5 -> x^7 ->
Then you make separate variable N1=x before loop and N1 *= x*2 at the end of each iteration
1 -> 1 -> 1x3 -> 1x3x5 -> 1x3x5x7 ->
Separate variable N2=1 before lopp and N2 *= (i*2-1) at the end of each iteration
etc, etc
finaly you will combine all this parts together at start of each iteration, like sum += N1*N2*N3/(N4*N5)
![enter image description here][1]The question:
Write a function with name ʻ expʼ that ,when given one integer x; returns
with the following approximation. In this function, you should use previous two functions to calculate factorial and power.
This is my code;
import java.util.Scanner;
public class ass7_q3 {
public static int power(int x, int y)
{
int result = 1;
for(int i = 1; i <= y; i++)
{
result = result * x;
}
return result;
}
public static int factorial(int n)
{
int fact = 1;
for(int i = 1; i<= n; i++)
fact = fact * i;
return fact;
}
public static int exp( int x)
{
int result;
result = (power(x,x) / factorial(x) );
return result;
}
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int sum = 0;
int x;
x = read.nextInt();
for(int i=0; i<=10; i++)
{
sum = sum + exp(x);
}
System.out.println(sum);
}
}
However, when I run this code, it always gives me the wrong answer.
What can I do?
You should start by working with doubles instead of integers. You can't expect to approximate a Real number using only integer calculations.
For example, power(x,x) / factorial(x) would always return an integer, since both methods return an int.
5/2 will return 2. You need cast it to double like ((double)5)/2 will return 2.5
You should think about range of integer ( in java 2,147,483,647)
if your input is grater than 12, integer can not handle.
Factorial method will return wrong value. because
factorial(12)=479,001,600 but
factorial(13)=6,227,020,800
Problem: Write a method that takes two integers n and m as parameters, and return the sum of alle the numbers (array of numbers) from n (including n) to m (including m).
public int getSum(int n, int m){
this.n = n;
this.m = m;
int [] x = {n,m};
int result = 0;
for(int i=0; i<x.length; i++){
result += x[i];
}
return result;
}
if n=1 and m=4 the method returns 5, but the method need to return 10, (1,2,3,4)=(1+2+3+4).
Guess this line is not right
int [] x = {n,m};
since the array will be {1,4} if n=1 and m=4. How to fix this, need to create the array {1,2,3,4} if n=1 and m=4
try this:
public int getSum(int n, int m){
int result = 0;
for(int i = n;i <= m;i++)
result += i;
return result;
}
or this:
public int getSum(int n, int m){
int result = 0;
while(n <= m)
result += n++;
return result;
}
or maybe with funny math:
public int getSum(int n, int m){
return (m*(m+1)/2) - ((n-1)*((n-1)+1)/2)
}
F(n) = (n*(n+1)/2) = 0+1+2+...+n
F(m) - F(n-1) = n + n+1 + n+2 + ... + m
Java 8
return IntStream.rangeClosed(n, m).sum();
#Andres has already given a perfect solution. But I wanted to explain some more, so here goes.
There are many problems with your code.
But yes, the central problem is the line. int [] x = {n,m};
What that line does is creates an array of just 2 numbers, and when you iterate over that array you are only adding those two numbers, not all the number in between.
In languages like C, C++, Java, etc... the simplest idiom to iterate over a range of numbers is
for(int i = n, i <=m, i++){
...
}
What this does is, create a temporary variable i and initialize it to the first number in the range n. And then run in the loop incrementing that temporary number i by one every time until it exceeds the last number of the range m.
Within the body of the loop each number of the range will now be available, for that iteration of the loop.
So in your case where you are summing up all the numbers, you can accumulate all those numbers in the range by setting up an accumulator variable like following.
int acc = 0;
for(int i = n, i <=m, i++){
acc = acc + i;
}
can't you just do this :
public static int getSum(final int n, final int m) {
// default value
int sum = 0;
// not permitted
if (n >= m)
return 0;
// all of the work here
for (int i = n; i <= m; i++)
sum += i;
return sum;
}
import java.util.Scanner;
import java.util.Arrays;
public class Improved {
//I resize the array here so that it only counts inputs from the user
//I want to ignore the 0 input from the user
//I think the error happens here or in my main method
public static double[] resizeArray(double[] numbers, double size) {
double[] result = new double[(int)size];
for (int i = 0; i < Math.min(numbers.length, size); ++i) {
result[i] = numbers[i];
}
return result;
}
//compute average nothing is wrong here
public static double getAverage( double[] numbers) {
double sum = 0;
for (int i = 0; i < numbers.length; ++i)
sum += numbers[i];
double average = sum/numbers.length;
return average;
}
//SD nothing is wrong here
public static double getSD( double[] numbers, double average) {
double sd = 0;
for ( int i = 0; i < numbers.length; ++i)
sd += ((numbers[i] - average)*(numbers[i] - average)/ numbers.length);
double standDev = Math.sqrt(sd);
return standDev;
}
//maximum nothing is wrong here
public static double getMax( double[] numbers) {
double max = numbers[0];
for (int i = 1; i < numbers.length; ++i)
if (numbers[i] > max){
max = numbers[i];
}
return max;
}
//minimum nothing is wrong here
public static double getMin( double[] numbers) {
double min = numbers[0];
for (int i = 1; i < numbers.length; ++i)
if (numbers[i] < min) {
min = numbers[i];
}
return min;
}
//median value nothing is wrong here
public static double getmed( double[] numbers) {
double median;
if (numbers.length % 2 == 0)
median = (((numbers[numbers.length/2 - 1])
+ (numbers[numbers.length/2]))/2);
else
median = numbers[numbers.length/2];
return median;
}
//the problem is in the main method i think or in the call method to resize
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] statArr = new double[99];
double size = 0;
int i = 0;
System.out.println("Type your numbers: ");
double number = input.nextDouble();
//I don't want the zero in the array, I want it to be excluded
while (number != 0){
statArr[i] = number;
i++;
number = input.nextDouble();
++size;
if ( size == statArr.length) {
statArr = resizeArray(statArr, statArr.length * 2);
}
++size;
}
statArr = resizeArray(statArr, size);
java.util.Arrays.sort(statArr);
double average = getAverage(statArr);
System.out.println( "The average is " + getAverage(statArr));
System.out.println( "The standard deviation is " + getSD(statArr, average));
System.out.println( "The maximum is " + getMax(statArr));
System.out.println( "The minimum is " + getMin(statArr));
}
}
// I don't have any concerns with computing the math parts, but I can't seem to make it so my array ignores the 0 that ends the while loop. In other words, I want every number included up until the user enters the number 0. Everything else is right. Thank you very much!
You have ++size twice. This means your resizeArray method won't work correctly:
double[] result = new double[(int)size];
Here you're allocating more than what you actually want. This is why you're getting zeroes in your array. Java arrays are initialized to 0 (in case of numeric primitive types).
As Giodude already commented, I suggest you using List implementations (typically ArrayList) instead of arrays everytime you can.
Also size could be declared as int altogether and avoid that cast (and save some extremely slight memory), you're not using it as a double anywhere.