I have the following code
public void alearningrate(){
//adopt learningrate
System.out.println(errorpositive+""+learningrate);
if ((errorpositive&&errorgradient>0)||!errorpositive&&errorgradient<0){
learningrate=learningrate*1.5;
}else{
learningrate=learningrate*0.75;
}
if (learningrate<0.0001){
learningrate=0.0001;
}
}
public void lastblame(double blame){
errorpositive=errorgradient>0;
errorgradient= Math.exp(-value)/Math.pow(1+Math.exp(-value), 2)*blame;
if (value==Double.NaN){
System.out.println("nan detected=?");
errorgradient=1;
}
for (int i=0; i<weight.length;i++){
weight[i]=weight[i]+learningrate*source[i].output()*errorgradient;
}
//alearningrate();
}
public void hiddenblame(double blame){
System.out.println(value);
errorpositive=errorgradient>0;
errorgradient=Math.exp(-value)/Math.pow(1+Math.exp(-value), 2)*blame;
if (value==Double.NaN){
System.out.println("nan detected=?");
errorgradient=1;
}
for (int i=0; i<weight.length;i++){
weight[i]=weight[i]+learningrate*source[i].output()*errorgradient;
}
System.out.println(errorgradient);
alearningrate();
}
however this causus the errorgradient to quickly become NaN, but if I decide to remove the alearningrate() then the code runs fine. I looked at my functions errorgradient function and it should never yield nan, anybody know why I keep getting NaN?
Related
I want to know if there are basic ways to call a method multiple times. I am not allowed to use for, if, or else statements. I am suppose to write a method called test 1 and test 2, which calls the increase speed and decrease speed by 3 times. If anyone can offer me suggestions, I would appreciate it.
Requirements
increaseSpeed. The increaseSpeed method should add 10 to the speed
field each time it is called.
reduceSpeed. The reduceSpeed method should subtract 10 from the speed
field each time it is called.
write a method called test1 that calls increaseSpeed three times.
write a method called test2 that calls reduceSpeed three times.
program:
public void increaseSpeed()
{
speed += 10;
}
public void reduceSpeed()
{
speed -= 5;
}
public void test1(){
}
public void test2(){
}
}
You could simulate a for loop with a while loop:
public void test1() {
int i = 0;
while (i < 3) {
increaseSpeed();
++i;
}
}
Or, if you aren't allowed to use loops at all, you could just call the increaseSpeed three times:
public void test1() {
increaseSpeed();
increaseSpeed();
increaseSpeed();
}
We can also get more creative (a.k.a. pointless):
This first example requires Java 8, but it's a glorified FOR loop. You can replace 'forEach' with a map() or filter() that has an ignored output or one of the other Java stream processing items if you have an aversion to the word 'for'.
private static void test1() {
IntStream.range(0, 3).forEach(
i -> increaseSpeed()
);
}
This second example uses a switch + recursion because you also didn't mention anything about the 'switch' statement.
private static final int INITIAL_COUNT = 2; // 3 - 1
private static int numTimes = INITIAL_COUNT;
private static void test2() {
switch(numTimes) {
case 0:
numTimes = INITIAL_COUNT;
break;
default:
numTimes--;
test2();
break;
}
reduceSpeed();
}
Note that if you tried to submit either of these to a code review, you'll be rejected unless the project is run by a joker that doesn't care about code quality :)
You didnt mention while loop is prohibited, i assume it is okay to use it:
int i = 0;
while(i<3){
increaseSpeed();
i++;
}
Alternatively, you can either use do-while loop to implement your requirement or invoke the method 3 times..
public void test1(){
increaseSpeed();
increaseSpeed();
increaseSpeed();
}
public void test2(){
decreaseSpeed();
decreaseSpeed();
decreaseSpeed();
}
For more general "solutions" and hacks have a look at these: C: Looping without using looping statements or recursion and
https://codegolf.stackexchange.com/questions/33196/loop-without-looping.
Using the given methods, the most effective and simple way would be to invoke it 3 times in a row:
public void test1() {
increaseSpeed();
increaseSpeed();
increaseSpeed();
}
public void test2() {
decreaseSpeed();
decreaseSpeed();
decreaseSpeed();
}
A more flexible approach is using a recursive invocation, as described below:
public void test1() {
increaseSpeed(3);
}
public void test2() {
decreaseSpeed(3);
}
private void increaseSpeed(int numTimes) {
if (numTimes == 0) {
return;
}
increaseSpeed();
increaseSpeed(numTimes-1);
}
private void decreaseSpeed(int numTimes) {
if (numTimes == 0) {
return;
}
decreaseSpeed();
decreaseSpeed(numTimes-1);
}
Going a little bit beyond the question, if these tests model a real use case it probably is a good idea to review methods increaseSpeed() and decreaseSpeed() to prevent these multiple invocations.
Your test1 method should be recursive and it should take an Integer as parameter which will be the number of calls you want to make
So basically you should have something like this:
public void test1(int nbcalls) {
if (nbcalls-- > 0) {
increaseSpeed();
test1(nbcalls);
}
}
and you call you method like this :
test1(3);
You should do the same with test2(...) method
I have a simple JForm that has some text fields.The problem is, my evaluate() method is not cycling through the text fields as I expected.All I get is the first text fields, of getText() that are executed. I'm stuck in this. Help would be great. Here is the code. Also here is a screen capture of the program: https://www.dropbox.com/s/w5ie4dfnc9wi216/Capture.JPG?dl=0
public MAppGest() {
initComponents();
}
public double a=2.6;
public double index0;
public Iterator itr;
public void getText(String ind, String inde){
evaluate();
index0=Double.parseDouble(txtNewIndex.getText())-Double.parseDouble(txtOldIndex.getText());
txtTotalIndex.setText(Double.toString(index0));
txtRoom1.setText(Double.toString(index0));
txtTotal1.setText(Double.toString((index0*a)));
}
public void evaluate(){
if(Boolean.valueOf(txtNewIndex.getText())&&Boolean.valueOf(txtOldIndex.getText())==true){
getArray();
}
else if(Boolean.valueOf(txtNewIndex2.getText())&&Boolean.valueOf(txtOldIndex2.getText())==true){
getArray();
}
else if(Boolean.valueOf(txtNewIndex3.getText())&&Boolean.valueOf(txtOldIndex3.getText())==true){
getArray();
}
else if(Boolean.valueOf(txtOldIndex4.getText())&&Boolean.valueOf(txOldIndex4.getText())==true){
getArray();
}
else if(Boolean.valueOf(txtNewIndex5.getText())&&Boolean.valueOf(txtOldIndex5.getTex())==true){
getArray();
}
else{
JOptionPane.showMessageDialog(MAppGest.this,"An error occured");
}
}
public void getArray() {
ArrayList<String> al=new ArrayList<>();
al.add(txtNewIndex.getText());
al.add(txtOldIndex.getText());
al.add(txtNewIndex2.getText());
al.add(txtOldIndex2.getText());
al.add(txtNewIndex3.getText());
al.add(txtOldIndex3.getText());
al.add(txtOldIndex4.getText());
al.add(txOldIndex4.getText());
al.add(txtNewIndex5.getText());
al.add(txtOldIndex5.getText());
for (int i = 0; i< al.size(); i++) {
String fields []=null;
fields[i] = al.get(i);
}
}
private void btnGrandTotalActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
getText(txtNewIndex.getText(),txtOldIndex.getText());
getText(txtNewIndex2.getText(),txtOldIndex2.getText());
getText(txtNewIndex3.getText(),txtOldIndex3.getText());
getText(txtOldIndex4.getText(),txOldIndex4.getText());
getText(txtNewIndex5.getText(),txtOldIndex5.getText());
}
If your problem is that evaluate() is only completing the first if statement, it's because you are using if-else statements when you want to just use if. If you use if-else, once the first if is verified true it will skip the rest. If my answer is not what you are looking for, then I advise you to ask a better question. Like the comments have said, give an SSCCE so the answerers aren't left guessing.
A side note: Boolean.valueOf() returns a boolean, so your ==true is unnecessary.
I've been working on my college assignment about stacks in java, but I can't seem to find the help for this assignment. It's about switchbox routing and I'm required to use stack for this assignment. The assignment is due tomorrow, but there's no need to rush for answers since I'm only looking for the solutions and not the grades. Since the problem isn't written in english, I'm going to give short explanation.
The switchbox contains 4n pins, with n pins on each side of the box. The switchbox is routable only when none of the lines connecting a pair of pins intersect another. The input will be pairs of connected pin numbers.
A few possible solutions I've found but can't understand:
1. The problem can be solved with a similar algorithm as the one for the parentheses matching
2. Putting the pin numbers in stack and an array and compare them (this is the most confusing one)
My code so far (trying the second algorithm):
import java.util.Scanner;
import java.util.Stack;
public class Tester {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int cases=sc.nextInt();
for(int i=0;i<cases;i++){
int pin=sc.nextInt();
SwitchBox box=new SwitchBox(pin);
for(int j=0;j<pin*4;j++){
box.add(sc.nextInt());
}
boolean res=box.isRoutable();
if(res){
System.out.println("routable");
}
else{
System.out.println("not routable");
}
}
}
static class SwitchBox{
Stack<Integer> pins;
int[] pairs;
int[] comparator;
public SwitchBox(int pin){
this.pins=new Stack<Integer>();
this.pairs=new int[(pin*4)];
this.comparator=new int[this.pairs.length];
}
public boolean isRoutable(){
Stack<Integer> s=new Stack<Integer>();
for(int i=0;i<pairs.length;i++){
pairs[i]=pins.peek();
s.push(pins.pop());
}
for(int i=pairs.length-1;i>=0;i--){
if(pairs[i]!=s.pop()){
return true;
}
}
return false;
}
public void add(int pinNum){
if(pins.isEmpty()){
pins.push(pinNum);
}
else{
Stack<Integer> temp=new Stack<Integer>();
int top=(int)pins.peek();
while(top>pinNum){
temp.push(pins.pop());
if(pins.isEmpty()) top=pinNum;
else top=(int)pins.peek();
}
pins.push(pinNum);
while(!temp.isEmpty()){
pins.push(temp.pop());
}
}
}
}
}
In your add method else block is wrong. I was unable to understand what you try to do but you need to do next thing
public void add(int pinNum) {
if (pins.isEmpty()) {
pins.push(pinNum);
} else {
Integer last = pins.peek();
if (last == pinNum) {
pins.pop();
} else {
pins.push(pinNum);
}
}
}
After that isRoutable method just need to check pins stack. If it empty, then all fine. Else there are intersecting lines.
I am trying to solve this question from talent buddy.
http://www.talentbuddy.co/challenge/52a9121cc8a6c2dc91481f8d5233cc274af0110af382f40f
My code compiles and runs for small input, but is giving wrong ans for the following input-
http://tb-eval4.talentbuddy.co/5411559648d3e7eb5100024191810645628720530000.html
My Code is as follows -
import java.util.*;
class MyClass {
public void tweets_per_second(Integer[] tps, Integer k) {
PriorityQueue<Integer> pq =new PriorityQueue<Integer>(k, new Comparator<Integer>(){
public int compare(Integer i1, Integer i2){
if (i1.intValue()< i2.intValue()){
return 1;
}
else if(i1.intValue() ==i2.intValue()){
return 0;
}
else {
return -1;
}
}
});
for(int i=0;i<tps.length;i++){
if (pq.size()<=k){
pq.add(tps[i]);
System.out.println(pq.peek());
}
else{
pq.remove(tps[i-k]);
pq.add(tps[i]);
System.out.println(pq.peek());
}
}
}
public static void main(String[] args) {
MyClass t = new MyClass();
Integer[] tps = {6,9,4,7,4,1};
t.tweets_per_second(tps, 3);
}
}
Can someone please let me know what am I doing wrong? Any help will be appreciated. Thanks.
The code is entirely correct. At the end of the page you can see the following:
Error: your code didn't finish in less than 2 seconds.
Which tells you all you need to know.
As to why your code is slow - while using PriorityQueue or any built in collections etc is overall a good idea, it is very much not so in this case. I don't want to make educated guesses about how it's implemented, but one of add, remove, peek is not O(1) and eats up your time.
can someone tell if the code below would work fine?
class CriticalSection{
int iProcessId, iCounter=0;
public static boolean[] freq = new boolean[Global.iParameter[2]];
int busy;
//constructors
CriticalSection(){}
CriticalSection(int iPid){
this.iProcessId = iPid;
}
int freqAvailable(){
for(int i=0; i<
Global.iParameter[2]; i++){
if(freq[i]==true){
//this means that there is no frequency available and the request will be dropped
iCounter++;
}
}
if(iCounter == freq.length)
return 3;
BaseStaInstance.iNumReq++;
return enterCritical();
}
int enterCritical(){
int busy=0;
for(int i=0; i<Global.iParameter[2]; i++){
if(freq[i]==true){
freq[i] = false;
break;
}
}
//implement a thread that will execute the critical section simultaneously as the (contd down)
//basestation leaves it critical section and then generates another request
UseFrequency freqInUse = new UseFrequency;
busy = freqInUse.start(i);
//returns control back to the main program
return 1;
}
}
class UseFrequency extends Thread {
int iFrequency=0;
UseFrequency(int i){
this.iFrequency = i;
}
//this class just allows the frequency to be used in parallel as the other basestations carry on making requests
public void run() {
try {
sleep(((int) (Math.random() * (Global.iParameter[5] - Global.iParameter[4] + 1) ) + Global.iParameter[4])*1000);
} catch (InterruptedException e) { }
}
CriticalSection.freq[iFrequency] = true;
stop();
}
No, this code will not even compile. For example, your "UseFrequency" class has a constructor and a run() method, but then you have two lines CriticalSection.freq[iFrequency] = true; and
stop(); that aren't in any method body - they are just sitting there on their own.
If you get the code to compile it still will not work like you expect because you have multiple threads and no concurrency control. That means the different threads can "step on eachother" and corrupt shared data, like your "freq" array. Any time you have multiple threads you need to protect access to shared variables with a synchronized block. The Java Tutorial on concurrency explains this here http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html
Have you tried compiling and testing it? Are you using an IDE like Eclipse? You can step through your program in the debugger to see what its doing. The way your question is structured no one can tell either way if your program is doing the right or wrong thing, because nothing is specified in the comments of the code, nor in the question posed.