I am having a little issue with formatting returned methods in the main method. I have created the methods and done the calculation, but my issue is if i am calling the other two methods to the main method correctly. I am also having and issue with formatting each method in columns. Do i need to make the columns in the respected methods? or do i need to create them in the main method?
Write a program that analyzes an object falling for 10 seconds. It should contain main and two additional methods. One of the additional methods should return the distance an object falls in meters when passed the current second as an argument. See the formula needed below. The third method should convert meters to feet. You can look up the conversion factor needed online. The main method should use one loop to call the other methods and generate a table as shown below. The table should be displayed in formatted columns with decimals as shown. I believe i am on
SEC METERS FEET
1 4.9 16.1
2 19.6 64.3
3 44.1 144.7
4 78.4 257.2
5 122.5 401.9
6 176.4 578.7
7 240.1 787.7
8 313.6 1028.9
9 396.9 1302.2
10 490.0 1607.6
My code
package week4.yedkois;
public class project3 {
public static void main(String[] args) {
System.out.printf("SEC" + "\n");
meters();
feet();
for (int time = 1; time <= 10; time++) {
System.out.println(time);
}
}
public static void meters() {
double Meters;
double G = 9.8; // meters = .5(9.8)(seconds) ^2
for (int time = 1; time <= 10; time++) {
Meters = (.5 * 9.8 * Math.pow(time, 2));
System.out.printf("%.1f\n", Meters);
}
return;
}
public static void feet() {
double Feet;
double G = 9.8; // meters = .5(9.8)(seconds) ^2
for (int time = 1; time <= 10; time++) {
Feet = (.5 * 9.8 * Math.pow(time, 2) * 3.28084);
System.out.printf("%.1f\n", Feet);
}
return;
}
}
Here is my solution. I use a Tab ("\t") to achieve the same space between the different values. And then I had to redesign your code a little. I use only one if-loop directly in the main-method and hand the current time-value as a parameter into both methods meters() and feet(). That makes it much easier to get all values of one round in line.
Here are some additional remarks:
Java is not C++, so you don't have to use an empty return statement at the end of a method. It's useless there.
In Java variables and method-names always start with a small letter, _ or $. Only class-names and constants start with a capital letter.
Hope this helps for a start.
public class Project3 {
public static void main(String[] args){
System.out.printf("%3s\t%6s\t%6s\n", "SEC", "METERS", "FEET");
for(int time = 1; time <= 10; time++)
{
System.out.print(time + "\t");
meters(time);
feet(time);
System.out.println();
}
}
public static void meters(int time){
double meters;
double g = 9.8; // meters = .5(9.8)(seconds) ^2
meters = (.5 * 9.8 * Math.pow(time, 2));
// the longer the expected maximum length of a result gets
// the higher your reserved number of digits has
// to be, to gain the wanted right bound effect!
System.out.printf("%6.1f\t", meters);
}
public static void feet(int time){
double feet;
double g = 9.8; // meters = .5(9.8)(seconds) ^2
feet = (.5 * 9.8 * Math.pow(time, 2) * 3.28084);
// the longer the expected maximum length of a result gets
// the higher your reserved number of digits has
// to be, to gain the wanted right bound effect!
System.out.printf("%6.1f", feet);
}
}
Related
So, I'm trying to get the decimals in a table I have for a gravity program that I created to round after 4 decimals. However, whenever I've tried to round it, it either will print the table without rounding, or it will start to print the table, and then throw an error at me.
I'm sure what I doing wrong, and I've tried to look online for help, but it hasn't helped.
I have a few lines commented out below to show where I have tried to round to 4 decimals places, but hasn't worked.
I'll post my code below to see if you guys could please help me figure out what I'm doing wrong.
public class Gravity
{
public static void main(String[] args)
{
Gravity g = new Gravity();
System.out.printf("%5s%20s%20s\n", "Time", "Distance Earth", "Distance Moon");
// Gravity.format()
// DecimalFormat df = new DecimalFormat("###.####");
// System.out.println(df.format(g));
for (int i = 1; i <= 10; i++)
{
System.out.printf("%5d%20fm%20fm\n", + i,g.distanceFallen(i, 9.8), g.distanceFallen(i, 1.625));
// System.out.format("%.4f", i);
}
}
/* private static Gravity format(String string, int i)
{
//
return i;
}*/
public double distanceFallen (double time, double gAcc)
{
// System.out.format("%.4f");
// System.out.format("%.4f", time);
return (0.5)*gAcc*Math.pow(time, 4);
}
}
EDIT: Also, here's what the table looks like, just to make clear up any potential confusion.
Time Distance Earth Distance Moon
1 4.900000m 0.812500m
2 78.400000m 13.000000m
3 396.900000m 65.812500m
4 1254.400000m 208.000000m
5 3062.500000m 507.812500m
6 6350.400000m 1053.000000m
7 11764.900000m 1950.812500m
8 20070.400000m 3328.000000m
9 32148.900000m 5330.812500m
10 49000.000000m 8125.000000m
Change your formatting to:
"%5d%20.4fm%20.4fm\n"
You'll want to change your header formatting to 24 instead of 20 too.
I have a program that takes in anywhere from 20,000 to 500,000 velocity vectors and must output these vectors multiplied by some scalar. The program allows the user to set a variable accuracy, which is basically just how many decimal places to truncate to in the calculations. The program is quite slow at the moment, and I discovered that it's not because of multiplying a lot of numbers, it's because of the method I'm using to truncate floating point values.
I've already looked at several solutions on here for truncating decimals, like this one, and they mostly recommend DecimalFormat. This works great for formatting decimals once or twice to print nice user output, but is far too slow for hundreds of thousands of truncations that need to happen in a few seconds.
What is the most efficient way to truncate a floating-point value to n number of places, keeping execution time at utmost priority? I do not care whatsoever about resource usage, convention, or use of external libraries. Just whatever gets the job done the fastest.
EDIT: Sorry, I guess I should have been more clear. Here's a very simplified version of what I'm trying to illustrate:
import java.util.*;
import java.lang.*;
import java.text.DecimalFormat;
import java.math.RoundingMode;
public class MyClass {
static class Vector{
float x, y, z;
#Override
public String toString(){
return "[" + x + ", " + y + ", " + z + "]";
}
}
public static ArrayList<Vector> generateRandomVecs(){
ArrayList<Vector> vecs = new ArrayList<>();
Random rand = new Random();
for(int i = 0; i < 500000; i++){
Vector v = new Vector();
v.x = rand.nextFloat() * 10;
v.y = rand.nextFloat() * 10;
v.z = rand.nextFloat() * 10;
vecs.add(v);
}
return vecs;
}
public static void main(String args[]) {
int precision = 2;
float scalarToMultiplyBy = 4.0f;
ArrayList<Vector> velocities = generateRandomVecs();
System.out.println("First 10 raw vectors:");
for(int i = 0; i < 10; i++){
System.out.print(velocities.get(i) + " ");
}
/*
This is the code that I am concerned about
*/
DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.DOWN);
long start = System.currentTimeMillis();
for(Vector v : velocities){
/* Highly inefficient way of truncating*/
v.x = Float.parseFloat(df.format(v.x * scalarToMultiplyBy));
v.y = Float.parseFloat(df.format(v.y * scalarToMultiplyBy));
v.z = Float.parseFloat(df.format(v.z * scalarToMultiplyBy));
}
long finish = System.currentTimeMillis();
long timeElapsed = finish - start;
System.out.println();
System.out.println("Runtime: " + timeElapsed + " ms");
System.out.println("First 10 multiplied and truncated vectors:");
for(int i = 0; i < 10; i++){
System.out.print(velocities.get(i) + " ");
}
}
}
The reason it is very important to do this is because a different part of the program will store trigonometric values in a lookup table. The lookup table will be generated to n places beforehand, so any velocity vector that has a float value to 7 places (i.e. 5.2387471) must be truncated to n places before lookup. Truncation is needed instead of rounding because in the context of this program, it is OK if a vector is slightly less than its true value, but not greater.
Lookup table for 2 decimal places:
...
8.03 -> -0.17511085919
8.04 -> -0.18494742685
8.05 -> -0.19476549993
8.06 -> -0.20456409661
8.07 -> -0.21434223706
...
Say I wanted to look up the cosines of each element in the vector {8.040844, 8.05813164, 8.065688} in the table above. Obviously, I can't look up these values directly, but I can look up {8.04, 8.05, 8.06} in the table.
What I need is a very fast method to go from {8.040844, 8.05813164, 8.065688} to {8.04, 8.05, 8.06}
The fastest way, which will introduce rounding error, is going to be to multiply by 10^n, call Math.rint, and to divide by 10^n.
That's...not really all that helpful, though, considering the introduced error, and -- more importantly -- that it doesn't actually buy anything. Why drop decimal points if it doesn't improve efficiency or anything? If it's about making the values shorter for display or the like, truncate then, but until then, your program will run as fast as possible if you just use full float precision.
i have this code, variables first, second and third only can obtain in double i need format in percent to write later on other place
import java.text.DecimalFormat;
public class Main {
public static void main(String[] argv) throws Exception {
double first = 0.5;
double second = 1.5;
double third = 2.5;
DecimalFormat df = new DecimalFormat("#%");
System.out.println(df.format(first));
System.out.println(df.format(second));
System.out.println(df.format(third));
}
}
output:
50%
150%
250%
i need obtain this result
-50%
50%
150%
i hope any can help me with this thanks
I looks like you need values relative to 100%, so you just need to subtract 1 (i.e. 100%) from your values:
System.out.println(df.format(first - 1));
System.out.println(df.format(second - 1));
System.out.println(df.format(third - 1));
I want to actively calculate the moving average of stock data using the formula below:
public class Average {
private static double usdJpy;
private int counter = 1;
private double movingAverageUsdJpy_ = 100.5;
public void calculateAverage(){
ReadData myData = new ReadData();
usdGbp = myData.getUsdGbp();
usdJpy = myData.getUsdJpy();
System.out.println("Before: " + movingAverageUsdJpy_);
movingAverageUsdJpy_ = (counter * movingAverageUsdJpy_ + usdJpy) / (counter + 1);
counter++;
System.out.println("Moving Average: " + movingAverageUsdJpy_);
}
}
-> Counter is the number of elements in the array.
My question is since the stock data already has a moving average, I want to set my initial movingAverage value to that (e.g 97.883). However, every time I call my method, the latest value that my program calculated for the movingAverage will be overwritten by the initial value I have set earlier, hence giving me the wrong result. I can't really use final because the movingAverage needs to be updated each time I call the method so really stuck!
Is there a way to fix this problem??
Your formula is incorrect. If counter is the not-yet incremented value, then use
movingAverage = (counter * movingAverage + latestRate) / (counter + 1)
Then increment counter by 1. Note that if you want counter to be fixed in size (as is quite common when reporting financial data like this), then you need to keep that number of elements in memory.
You probably have something like:
class Something{
public int calculateAverage(){
int movingAverage = 98888;
//more code to count average
}
}
What you need to do is:
class Something{
private int myAverage = 98888;
public int calculateAverage(){
//code to calculate using myAverage variable;
}
}
Create a new private field used for storing the previous average. I'm not very familiar with moving averages per say, but using the formula you've provided I've adjusted things a bit. Note, typically an underscore is used to indicate that a class level variable is private
private double movingAverage_;
private double prevAverage_ = 97.883;
public void calculateMovingAverage()
{
movingAverage_ = prevAverage_ + (latestRate - prevAverage_)/counter;
prevAverage_ = movingAverage_;
// finish other logic
}
I am encountering a problem when creating a program to solve simple kinematics.
I run the program and find out the fields haven't been modified properly . Here is
the scrap of my program that initialise the object and setting the variables.
public class LinearConstantAcceleration1DKinematics {
private double distance;
private double speed;
private double acceleration;
private double time;
public LinearConstantAcceleration1DKinematics() {
/* initialize the object */
distance = 0;
speed = 0;
acceleration = 0;
time = 0;
}
public void setS(double s) {
this.distance = s;
}
//continue with 3 more setters which is created in the same way ,i have omitted them here
public double getU(){
double u_ans;
u_ans = (distance - 1/2 *acceleration*time*time )/time;
return u_ans;
}
}
And here is the main that uses the methods
LinearConstantAcceleration1DKinematics kinematics = new LinearConstantAcceleration1DKinematics();
kinematics.setS(175);
kinematics.setA(10);
kinematics.setT(5);
System.out.printf(%f\n", kinematics.getU());
The result is 35 which is incorrect.Many thanks for your help.
This has absolutely nothing to do with setter methods -- your division is wrong since 1 / 2 does int division and returns 0 resulting in the equation calculating simply distance / time.
Change to:
u_ans = (distance - 1.0 / 2.0 * acceleration * time * time) / time;
Lesson to learn: don't assume where the error is -- test it. Use a debugger or println statements to check the states of your variables as your program runs.