Summing up products from java loop - java

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;
}

Related

sum of all prime numbers between 100 and 200

I'm actually about to loose my mind... The code I wrote displays every kind of "sum" and "count" between the actual last result I want to display with System.out.print(...). Can someone help me please? What did I do wrong for it to display everything?
public class Prim {
public static void main(String[] args) {
int end = 11;
int count = 1;
long sum = 0;
for (int number = 10; count<=end; number++) {
if (isPrim(number)) {
sum = sum + number;
count++;
System.out.println(sum);
}
}
}
public static boolean isPrim(int number){
for (int i=2; i<number; i++) {
if (number % i == 0) {
}
}
return true;
}
}
A few things.
First, your isPrim can be optimised so that i only increments until sqrt(number).
Second, you need to return false if (number%i == 0) is true. Right now, it's always returning true, which is why your code is outputting all sums.
Third, you need to change istPrimeZahl to isPrim (or vice versa), as you haven't defined istPrimeZahl anywhere.
Fourth, you can change sum = sum + number to simply sum += number.
Finally, you probably want to move your System.out.print line two lines below, so that it only prints the sum after the loop has ended, not at every iteration of the loop.
(Also, you might want to change your for loop so that it starts at 100, not 10 :) )
If you want the final version, I've pasted it here:
public class Prim {
public static void main(String[] args) {
int end = 200;
int count = 0;
long sum = 0;
for (int number = 100; number<=end; number++) {
if (isPrim(number)) {
sum += number;
count++;
System.out.println(sum);
}
}
}
public static boolean isPrim(int number){
for (int i=2; i*i<=number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
The isPrim function is missing a 'return false' after the if statement. This means that isPrim will always return true, and consequently every number will get written to the console.
The System.out.print is also within for-loop, so it will print an updated sum each time. It's unclear if this is intentional, but if you want to only get a single result then that should also be moved two lines lower.
For sum of prime numbers between 100 to 200, try this code:
public class Primzahlen {
public static void main(String[] args) {
int sum = 0;
for (int i = 100; i < 200; i++)
if (isPrim(i))
sum += i;
System.out.print(sum);
}
public static boolean isPrim(int num) {
for (int i = 2; i <= Math.sqrt(num); i++)
if (num % i == 0)
return false;
return true;
}
}

Use boolean to search for outliers of standard dev and then print the outliers using java

What I'm trying to do is figure out a way to print the outliers of standard deviation here. The outliers are defined as having a variance greater than 2x the standard deviation. I can't figure out how but I've started by creating a boolean flag, however I don't understand the dynamics of this. Could someone please help me figure out how to print out the outliers somehow? Thanks.
public class Main {
public static void main(String[] args)
{
{
Algebra n = new Algebra();
System.out.println(" ");
System.out.println("The maximum number is: " + n.max);
System.out.println("The minimum is: " + n.min);
System.out.println("The mean is: " + n.avg);
System.out.println("The standard deviation is " + n.stdev);
}
}
}
2nd part:
public class Algebra
{
static int[] n = createArray();
int max = displayMaximum(n);
int min = displayMinimum(n);
double avg = displayAverage(n);
double stdev = displayStdDev(n);
public boolean outliers() {
for(int i = 0; i < n.length; i++)
{
boolean flag = (n[i] < stdev*2);
}
return
}
public Algebra()
{
this(n);
System.out.println("The numbers that are outliers are ");
for(int i = 0; i < n.length; i++)
{
System.out.print(" " + (n[i] < stdev*2));
}
}
public Algebra(int[] n)
{
createArray();
}
public static int[] createArray()
{
int[] n = new int[100];
for(int i = 0; i < n.length; i++)
n[i] = (int)(Math.random()*100 + 1);
return n;
}
public int displayMaximum(int[] n)
{
int maxValue = n[0];
for(int i=1; i < n.length; i++){
if(n[i] > maxValue){
maxValue = n[i];
}
}
return maxValue;
}
public int displayMinimum(int[] n)
{
int minValue = n[0];
for(int i=1;i<n.length;i++){
if(n[i] < minValue){
minValue = n[i];
}
}
return minValue;
}
protected double displayAverage(int[] n)
{
int sum = 0;
double mean = 0;
for (int i = 0; i < n.length; i++) {
sum += n[i];
mean = sum / n.length;
}
return mean;
}
protected double displayStdDev(int[] n)
{
int sum = 0;
double mean = 0;
for (int i = 0; i < n.length; i++) {
sum = sum + n[i];
mean = sum/ n.length;
}
double squareSum = 0.0;
for (int i = 0; i < n.length; i++)
{
squareSum += Math.pow(n[i] - mean, 2);
}
return Math.sqrt((squareSum) / (n.length - 1));
}
}
Variance is defined as the squared difference from the mean. This is a fairly straight forward calculation.
public static double variance(double val, double mean) {
return Math.pow(val - mean, 2);
}
You define an outlier as an instance that has a variance greater than x2 the standard deviation.
public static boolean isOutlier(double val, double mean, double std) {
return variance(val, mean) > 2*std;
}
You then just need to iterate through the values and print any values that are evaluated as an outlier.
public void printOutliers() {
for (int i : n) {
if (isOutlier(i, avg, stdev)) {
...
}
}
}
You should note that if one value is defined as an outlier and subsequently removed, values previously classified as an outlier may no longer be. You may also be interested in the extent of an outlier in the current set; One value may be an outlier to a greater extent than another.

How to find mode of an array, if one exists. If more than one mode, return NaN [duplicate]

This question already has answers here:
Write a mode method in Java to find the most frequently occurring element in an array
(14 answers)
Closed 5 years ago.
As the title states, I need to find the mode of an array. However, there are a few stipulations to this:
1) If no mode exists (i.e. each element appears only once, or equal times) return Double.NaN
2) If more than one mode exists (i.e. {1,2,2,3,4,5,5,6} would give two modes, 2 and 5) return Double.NaN
Basically, it should only return an element of the array if it is definitely the mode of the array, and appears at least once more than all other elements. Any other time, it should return Double.NaN
My current code returns a mode. However, if two numbers appear equally, it returns the latter of the two as the mode, not NaN. Also, doesn't return NaN if no mode exists.
Any help is appreciated.
Here is what I have so far:
public double mode(){
double[] holder = new double[data.length];
double tempMax = 0, permMax = 0, location = 0, arrayMode = 0;
for (int i = 0; i < data.length; ++i) {
int count = 0;
for (int j = 0; j < data.length; ++j) {
if (data[j] == data[i])
++count;
}
holder[i] = count;
}
for (int w = 0; w < holder.length; w++){
if (holder[w] > tempMax){
tempMax = holder[w];
arrayMode = data[w];
}
}
permMax = arrayMode;
return permMax;
}
It is fairly easy to find a duplicate for this question, e.g. here.
That being said, I'd like to add another solution:
public double findMode(int[] inArray) {
List<Integer> il = IntStream.of(inArray).boxed().collect(Collectors.toList());
int maxFreq = 0;
double value = 0;
for (Integer i : ia){
if (Collections.frequency(il, i) > maxFreq && i != value){
maxFreq = Collections.frequency(il, i);
value = i;
} else if (Collections.frequency(il, i) == maxFreq && i != value) {
value = Double.NaN;
}
}
return value;
}
It turns the int[] into a List<Integer> and uses the Collections.frequency method to get the number of occurrences of each value.
Disclaimer: there are likely some optimizations that I missed.
The best way to do it is to sort your array, then go through it from start to finish counting the number of instances of each number against the max found so far. If you really need to keep the original order of your numbers, first duplicate the array
public static double mode (double[] data) {
double maxnum = Double.NaN;
double num = 0;
int maxcount = 0;
int count = 0;
double[] used = Arrays.copyOf(data, data.length);
Arrays.sort(data);
for (int i = 0; i < used.length; i++) {
if (used[i] == num) {
count++;
}
else {
num = used[i];
count = 1;
}
if (count == maxCount) {
maxnum = Double.NaN;
}
if (count > maxCount) {
maxnum = num;
maxcount = count;
}
}
return maxnum;
}

How to solve "the birthday paradox" in java without using nested loop?

I have tried the problem with nested loop, but how can I solve it without using nested loops and within the same class file. The Question is to find the probability of two people having the same birthday in a group. And it should produce the following output : In a group of 5 people and 10000 simulations, the probability is 2.71%. Note: using arraylist or hashmap is possible. But I don't know how. Thank you
public void process() {
int groupSize = System.out.getSize();
int simulationCount = System.out.getCount();
if (groupSize < 2 || groupSize > 365) {
System.out.makeAlertToast("Group Size must be in the range 2-365.");
return;
}
if (simulationCount <= 0) {
System.out.makeAlertToast("Simulation Count must be positive.");
return;
}
double percent = calculate(groupSize, simulationCount);
// report results
System.out.println("For a group of " + groupSize + " people, the percentage");
System.out.println("of times that two people share the same birthday is");
System.out.println(String.format("%.2f%% of the time.", percent));
}
public double calculate(int size, int count) {
int numTrialSuccesses = 0;
// Repeat and count.
for (int n=0; n < count; n++) {
Random rand = new Random(n);
// Generate birthdays (random array)
int[] birthdays = new int [size];
for (int i=0; i <size; i++) {
birthdays[i] = rand.nextInt (365);
}
// Check if any two match.
boolean matchExists = false;
for (int i=0; i < size; i++) {
for (int j=0; j < size; j++) {
if ( (i != j) && (birthdays[i] == birthdays[j]) ) {
// Note: musn't forget the i!=j test above!
matchExists = true;
if (matchExists) break;
}
}
}
if (matchExists) {
numTrialSuccesses ++;
}
} //end-for-trials
double prob = ((double) numTrialSuccesses *100)/ (double) count;
return prob ;
}
}
A solution using fancy data structure HashSet. As some mentioned in the comments you could use an 365 element array of bools which you switch to true if encountered.
The below is a similar idea. You add each birthday to the set if it does not contain the birthday yet. You increment the counter if the Set does contain the birthday. Now you don't need that pesky second iteration so your time complexity goes down to O(n). It goes down to O(n) since a lookup in a set has constant time.
public double calculate(int size, int count) {
int numTrialSuccesses = 0;
// Repeat and count.
for (int n=0; n < count; n++) {
Random rand = new Random(n);
Set<Integer> set = new HashSet<Integer>();
for (int i=0; i <size; i++) {
int bday = rand.nextInt (365);
Integer bday1 = new Integer(bday);
if(set.contains(bday1)){
numTrialSuccesses++;
break;
}else{
set.add(bday1);
}
}
} //end-for-trials
double prob = ((double) numTrialSuccesses *100)/ (double) count;
//like wise comments have noted this is not the probability!!! Just a simulation
return prob ;
}
This code:
int[] birthdays = new int [size];
for (int i=0; i <size; i++) {
birthdays[i] = rand.nextInt (365);
}
// Check if any two match.
boolean matchExists = false;
for (int i=0; i < size; i++) {
for (int j=0; j < size; j++) {
if ( (i != j) && (birthdays[i] == birthdays[j]) ) {
// Note: musn't forget the i!=j test above!
matchExists = true;
if (matchExists) break;
}
}
}
if (matchExists) {
numTrialSuccesses ++;
}
can be changed to:
List<Integer> list = new ArrayList<Integer>();
for (int i=0; i <size; i++) {
int day=rand.nextInt (365);
if(list.contains(day)){
numTrailSuccesses++;
break;
}else{
list.add(day);
}
}
In java-8,
double calculateProbability(int trials, int people) {
//for trials = 10_000, people = 5
int timesWithSharedBirthday = IntStream.range(0,trials) // Run 10_000 trials
// generate 5 bdays, count distinct ones. Filter out those with 5 distinct
.filter(i -> ThreadLocalRandom.current().ints(people,1,365).distinct().count() != people)
.count(); // Add up the runs without five distinct bdays.
return probability = 100.0 * timesWithSharedBirthday / trials;
}
I don't know how it will fare with your online grader, but it's fun to practice with streams.
There isn't any need to go beyond primitives with something like a fixed number of birthdays.
Create an array of 365 buckets, and make a note in each bucket of when a birthday hit that date. This allows the use of efficient array operations.
Rather than creating a new array each time, the code below uses System.arraycopy to copy a zeroed-out array over the existing one--this gains a bit of performance.
Nevertheless, the performance gain over the HashSet example given earlier is modest at best, performing 5 or 6 times faster, but not orders of magnitude faster.
As such, if using HashSet and similar tools improves clarity, then go for clarity.
public double calculate(int size, int count) {
int numTrialSuccesses = 0;
int[] daysOfYear = new int[365];
final int[] empty = new int[365];
// Repeat and count.
for (int n = 0; n < count; n++) {
Random rand = new Random(n);
// Efficiently clear out the array
System.arraycopy(empty, 0, daysOfYear, 0, 365);
boolean matchExists = false;
for (int i = 0; i < size; i++) {
int birthday = rand.nextInt(365);
// Compare, then increment, the bucket for the birthday
if(daysOfYear[birthday]++>0){
matchExists = true;
break;
}
}
if (matchExists) {
numTrialSuccesses++;
}
} //end-for-trials
double prob = ((double) numTrialSuccesses * 100) / (double) count;
return prob;
}

Getting the wrong output? My coding is maybe off?

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;
}

Categories