JAVA LOOP FOR NEWTON RAPHSONS METHOD - java

I know the code below is a bit rough , i just need to get it to work before i clean it up. I'm working on newton raphson's methood that repeats as long as a condition is through. here's what i've got so far
import java.util.Scanner;
import static java.lang.System.out;
import static java.lang.System.in;
public class NewtonRaphson {
public static float intervalfunctions(float b){
return ((b*b*b)-3*b+1);
}
public static float differentiatedfunctions(float b) {
return (3*(b*b)-3);
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner myScanner = new Scanner(in);
out.println("PROGRAMME TO SOLVE NEWTON'S SCHEME");
float E, Z, F, D, G,FF,fa,fb,b,fx,ffx,x1;
float x[] = new float[10];
out.println("Enter the accauracy required");
E = myScanner.nextFloat();
out.println("Enter the first Interval");
D = myScanner.nextFloat();
out.println("Enter the final interval");
G = myScanner.nextFloat();
fa = intervalfunctions(D);
fb = intervalfunctions(G);
if ((fa * fb)<0) {
out.println("The Solution exists between the given interval");
x[0] = (D+G)/2;
fx = intervalfunctions(x[0]);
ffx = differentiatedfunctions(x[0]);
x[1] = x[0] - (fx/ffx);
out.println("x[1] is ");
out.print(x[1]);
}
now i need a way to loop x and differentiated functions for the next values where x0 changes to x1 and x1 to x2 on and on to an error tolerance of 10^-2. i know i'll definitely need a while loop and maybe a for loop , but i need a way to loop through my x array .. i couldnt do this for (x[1++]) . i'll also need a way to loop my methods for each new value of x.

I can't say I'm following what you are trying to calculate, but if I understood your explanation, you need a loop similar to this :
x[0] = (D+G)/2;
fx = intervalfunctions(x[0]);
ffx = differentiatedfunctions(x[0]);
for (int i = 1; i < 10; i++) {
x[i] = x[i-1] - (fx/ffx);
fx = intervalfunctions(x[i]);
ffx = differentiatedfunctions(x[i]);
}

Related

How to brute force a math equation in a way that does not slow down an Android app

I am building a math game for Android using Java. It includes a 3x3 grid of numbers that the user has to solve using mathematical operations. Before the start of the game, three random numbers 1-6 are rolled.
However, during my testing, I have discovered that some of the numbers are not solvable, say 4, with 1, 1, 1. (These numbers would never be rolled, but you get the point.)
I am using MxParser to find if the generated equation is correct, but the help I need is on how to create valid math equations.
I have decided to take the brute-force approach, but I am unsure as how to create valid mathematical equations with that method. It would have to generate equations like:
(Our numbers are: 1, 2, 3)
12^03^0 = 1 (True) Next number #1
12^03^0 = 2 (True) Next number #2
12^23^2 = 13 (False) Try again. #3
And so on.
I have tried brute-forcing already, but am unsure exactly how to do so.
`
import org.mariuszgromada.math.mxparser.Expression;
import java.util.ArrayList;
public class GridParser {
public String num1String = "";
public String num2String = "";
public String num3String = "";
private static String l;
private static String q;
private static String a;
private static int p;
private static char[] w;
private static char[] c;
public void parseGrid(int num1, int num2, int num3, int gridID) {
num1String = String.valueOf(num1);
num2String = String.valueOf(num2);
num3String = String.valueOf(num3);
String operator1 = "+";
String operator2 = "-";
String operator3 = "/";
String operator4 = "*";
String operator5 = "^";
ArrayList solutions3x3 = new ArrayList();
ArrayList solutions4x4 = new ArrayList();
ArrayList solutions6x6 = new ArrayList();
String currentSolution = "";
double NumberOnGrid = 0.0;
int currentPOS = 0;
if (gridID == 3) {
NumberOnGrid = 3.0;
String l = "1234567890-()=+√*/^";
q = "";
p = 0;
w = a.toCharArray();
c = l.toCharArray();
while (!q.equals(a)) {
for (int i = 0; i < l.length(); i++) {
System.out.println("[❕] Trying: " + c[i]);
if (c[i] == w[p]) {
q += c[i];
p++;
System.out.println("[✔️] Found: " + c[i]);
Expression targetExpression = new Expression(q);
double expressonResult = targetExpression.calculate();
if(expressonResult == NumberOnGrid){
}
}
if (q.equals(a)) {
System.out.println("\n[✔️] Equation Found!");
}
}
}
}
}
}
I apologize for my code, it is still in "Rough Draft" state. =)
Additionally, it would be great if this could run on a background thread so it would not slow down my Android app.
Thanks
Someone PLZZZ help!

Java Assignment, add value to variable in different class

currently doing an assignemnt but i'm new to programming so was wondering how you add a value to a variable in a different class which already has an existing class
class OtherClass {
int a;
}
public class Main Class{
public static void main(String[] args) {
int b = 7;
OtherClass temp = new OtherClass();
OtherClass.a = 5
OtherClass.put(b) //this is where I'm not sure how to add b to a
}
Actual Code
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("Enter amount of money you have: ");
Scanner input = new Scanner(System.in);
Wallet bettersWallet = new Wallet();
bettersWallet.moneyAvailable = input.nextDouble(); //then had a function which played out a bet and added/took away winnings from the bet
int winnings = 5;
bettersWallet.moneyAvailable +=winnings; //Will setMoneyAvailable function work in this scenario aswell?
}
class Wallet {
double moneyAvailable;
double openingCash;
public void setMoneyAvailable()
{
moneyAvailable += ChuckALuckDiceGame.winnings;
}
int b = 7;
OtherClass temp = new OtherClass();
temp.a = 5;
temp.a += b; //Same as temp.a = temp.a + b;
System.out.println(temp.a);
What we are doing here,
We are creating an object of class OtherClass, the name of the object is temp.
Then we are assigning the value 5 in the attribute a of object temp
Then we are adding the value of primitive variable b into the variable temp.a.
The sum of the above equation is being assigned to the value of temp.a
Then I am printing the sum at the end through System.out.println(temp.a);

why isn't the rest of my method being called? (loop being ignored)

i'm trying to write a program that reads a file and then prints it out and then reads it again but only prints out the lines that begin with "The " the second time around. it DOES print out the contents of the file, but then it doesn't print out the lines that begin with "The " and i can't figure out why. it prints out the println line right before the loop, but then it ignores the for-loop completely. the only difference between my findThe method and my OutputTheArray method is the substring part, so i think that's the problem area but i don't know how to fix it.
import java.util.*;
import java.io.*;
public class EZD_readingFiles
{
public static int inputToArray(String fr[], Scanner sf)
{
int max = -1;
while(sf.hasNext())
{
max++;
fr[max] = sf.nextLine();
}
return max;
}
public static void findThe(String fr[], int max)
{
System.out.println("\nHere are the lines that begin with \"The\": \n");
for(int b = 0; b <= max; b++)
{
String s = fr[b].substring(0,4);
if(s.equals("The "))
{
System.out.println(fr[b]);
}
}
}
public static void OutputTheArray(String fr[], int max)
{
System.out.println("Here is the original file: \n");
for(int a = 0; a <= max; a++)
{
System.out.println(fr[a]);
}
}
public static void main(String args[]) throws IOException
{
Scanner sf = new Scanner(new File("EZD_readme.txt"));
String fr[] = new String[5];
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.findThe(fr,z);
sf.close();
}
}
this is my text file with the tester data (EZD_readme.txt):
Every man tries as hard as he can.
The best way is this way.
The schedule is very good.
Cosmo Kramer is a doofus.
The best movie was cancelled.
Try cloning sf and passing it to the other function.
Something like this:
Scanner sf = new Scanner(new File("EZD_readme.txt"));
Scanner sf1 = sf.clone();
int y = EZD_readingFiles.inputToArray(fr,sf);
EZD_readingFiles.OutputTheArray(fr,y);
int z = EZD_readingFiles.inputToArray(fr,sf1);
EZD_readingFiles.findThe(fr,z);
sf.close();
sf1.close();

Null pointer exception sketching a polygon [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
The Program I'm trying to make is supposed to draw a Polygon using points stored in an ArrayList. I rechecked the code and I am also using the driver, but when I try to run the program, it gives me a NullPointerException when I try to add coordinates for the program to use when drawing.
import java.awt.geom.*;
import java.util.ArrayList;
import gpdraw.*;
public class IrregularPolygon
{
private ArrayList <Point2D.Double> myPolygon;
DrawingTool myPen;
SketchPad myPaper;
double dblPerimeter;
double dblSegment;
double dblArea;
public IrregularPolygon()//Creating the sketchpad and pen
{
myPaper = new SketchPad(500,500);
myPen = new DrawingTool(myPaper);
}
public void add(Point2D.Double aPoint)//Adds to the array
{
myPolygon.add(aPoint);// This is where the problem is I think, I don't know what to do
}
public void draw()//This method draws the polygon
{
for(int x = 0; x < myPolygon.size() - 1 ; x++)
{
myPen.down();
myPen.move(myPolygon.get(x).getX(),myPolygon.get(x).getY());
myPen.up();
}
}
public double perimeter()//This method finds the perimeter
{
for(int x = 0; x < myPolygon.size() - 1; x++)
{
dblPerimeter += myPolygon.get(x).distance(myPolygon.get(x+1));
}
return dblPerimeter;
}
public double area()//This method finds the area
{
for(int x = 0; x < myPolygon.size() - 1; x++)
{
double X1 = (myPolygon.get(x).getX());
double Y1 = (myPolygon.get(x).getY());
double X2 = (myPolygon.get(x + 1).getX());
double Y2 = (myPolygon.get(x + 1).getY());
dblArea += (X1 * Y2 - Y1 * X2);
}
return dblArea;
}
}
and the programs runs from this driver:
import java.util.*;
import java.awt.geom.Point2D;
public class IrregularPolygonDriver
{
static boolean blnReadyToDraw = false;
static Scanner in = new Scanner(System.in);
public static void main(String[]args)
{
int num;
IrregularPolygon poly = new IrregularPolygon();
while(blnReadyToDraw == false)
{
System.out.println("Would you like to add a point, find the perimeter, or calculate the area?");
System.out.println("To add a point, enter 1; to find the perimeter, enter 2; to find the area, enter 3");
num = in.nextInt();
if(num == 1)
{
double dblNum1;
double dblNum2;
Point2D.Double dblNumber;
System.out.println("Enter an x value and a y value: ");
dblNum1 = in.nextDouble();
dblNum2 = in.nextDouble();
dblNumber = new Point2D.Double(dblNum1,dblNum2);
poly.add(dblNumber);
System.out.println("Keep adding points until you are done drawing the figure.");
}
else if(num == 2)
{
poly.perimeter();
}
else if(num == 3)
{
poly.area();
}
else
{
blnReadyToDraw = true;
System.out.println("Preparing to Draw");
}
}
poly.draw();
}
}
This is happening because your myPolygon is null.
Change:
private ArrayList <Point2D.Double> myPolygon;
To this:
private ArrayList <Point2D.Double> myPolygon = new ArrayList<>();
Or, in your constructor, add this line:
myPolygon = new ArrayList<>();
You didn't initialize your ArrayList,
private ArrayList <Point2D.Double> myPolygon;
is equivalent to
private ArrayList <Point2D.Double> myPolygon = null;
so when you say
myPolygon.add(aPoint); // <-- null.add(aPoint);
You could assign it in the constructor, or at declaration (using the List interface and the diamond operator <>) with something like
private List<Point2D.Double> myPolygon = new ArrayList<>();

Make a string variable from a random array

import java.util.Random;
public class DotComTestDrive {
public static void main(String [] args) {
String stringOfWords[] = {"Do", "You", "Like", "Me"};
boolean correctOrder = true;
int numberOfResets = 0;
String correctString;
String realString[];
while (correctOrder == true) {
System.out.println();
for (int x = 0 ; x < 4 ; x++) {
int rand = (int) (Math.random() * 4);
System.out.print(stringOfWords[rand]);
System.out.print(" ");
numberOfResets++;
}
// Place If statement here to change correctOrder to false when the new string is "Do You Like Me "
}
System.out.println(numberOfResets);
}
}
My main goal for this is to try and get the new random four words that
it prints out into an String[] so I can then use an If statement to
see if the string matches the original. Then I will make the boolean
"correctOrder" be false, ending the loop.
I know it is simple and sorry if its not a great or clear question.
Just trying to learn the basics and anything helps, thanks!
What I would suggest is to use a list and shuffle it every time you loop.
Map<K,V> map = xxxx;
List<Map.Entry<K,V>> list = new ArrayList<Map.Entry<K,V>>(map.entrySet());
// each time you want a different order.
Collections.shuffle(list);
for(Map.Entry<K, V> entry: list) { /* ... */ }
Assuming that you want to put these Strings in realString, you should do as follows/
initialise this Array
assign one of its elements in your for loop.
For example:
String realString[] = new String[4];
while(correctOrder == true){
for(int x = 0; x < 4; x++){
int rand = (int) (Math.random()*4);
System.out.print(stringOfWords[rand]);
System.out.print(" ");
realString[x] = stringOfWords[rand];
}
}
Also, since I'm at it, I'd suggest you to change a few things in your code:
no need to specify == true: a boolean variable can be tested by itself.
the use of the Random class (instead of Math one) is often preferred. You could have a final Random r = new Random() and get a random int in the range [0, 4[ by simply using r.nextInt(4)

Categories

Resources