I've been working on a Java project which is calculator which can be used for calculating different scenarios of compound interest (very similar to the TVM Function found on a graphics calculator like this one)
The main function of the calculator is to calculate missing values using the known values in a formula. I have gotten all of the formulas working except for the one which calculates Interest rate (I)
I have done some research and apparently there is no straight formula to calculate the interest rate. This website: http://www.getobjects.com/Components/Finance/TVM/formulas.html shows the method i need to use, but it requires some iteration to find I using trial and error. (Check the link, Scroll down to the heading "Interest Rate Per Year")
Here is the structure I have set up for it:
public static double calculateI(double N, double PV, double PMT, double FV, double PY){
//method for calculating I goes here
return I;
}
I am not sure how to implement this, could someone please suggest how this can be done or point me in the right direction?
Thanks in advance.
Here is my code after the suggestion made by #rocketboy
public static double formulaI(double ip, double N, double PV, double PMT, double FV, double PY){
double I1=(PV*Math.pow((1+ip),N))+((PMT*1)*(Math.pow((1+ip),N))-1)+FV;
return I1;
}
public static double calculateI(double N, double PV, double PMT, double FV, double PY){
double ip=0;
double res;
do{
res = formulaI(ip,N,PV,PMT,FV,PY);
ip=ip+0.01;
System.out.println(res);
}while(res!=0);
double I=ip*PY;
return I;
}
Try something like:
double calculateI(/*all values for varialbles*/){
//definition;
}
Double.valueOf(d).equals(0.0);
long ip =0;
double res;
do{
res = calculateI(ip, /*other constant values*/);
ip++; /*Or you can increase ip according to your logic*/
}while ( Double.valueOf(res).equals(0.0/*Expected result*/));
Edit: You have to handle the edge cases. The equation may not ever converge to 0.
Related
I'm trying to write a java program that will solve any ordinary differential equations using Euler method, but I don't know how to write a code to get any differential equation from the user. I was only able to write the code to solve a predefined ordinary differential equations.
I was able to come with a code to solve some particular ordinary differential equations which were written as functions in the program, I also made research online to look for similar problems but it seem they also wrote it to solve some designated problem not general questions on ordinary differential equations. This was found in most of the article have read online.
Here is my Euler class;
import java.lang.Math;
public class Euler {
private double x0, y0, x1, y1, h, actual;
public Euler (double initialx, double initialy,double stepsize,double finalx1) {
x0 = initialx; y0 = initialy; h=stepsize; x1 = finalx1;
}
public void setEuler (double initialx, double initialy,double stepsize,
double finalx1){
x0 = initialx;y0 = initialy;h =stepsize;x1 = finalx1;
}
public double getinitialx(){
return x0;
}
public double getinitialy(){
return y0;
}
public double getinitialexact(){
return (double) (0.9048*Math.exp(0.1*x0*x0));
}
double func(double x, double y){
return (double) (0.2*x*y);
}
double funct(double x){
return (double) (java.lang.Math.exp(0.1*x*x));
}
public double getinitialerror(){
return (double) Math.abs(actual - y0);
}
public double getEulerResult(){
for (double i = x0 + h; i < x1; i += h){
y0 = y0 + h *(func(x0,y0));
x0 += h;
double actual = (0.9048*funct(x0));
double error = Math.abs(actual - y0);
System.out.printf("%f\t%f\t%f\t%f\n",x0,y0,actual, error);
}
return y0;
}
}
Here is my Driver's class
import java.util.Scanner;
public class EulerTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Euler myEuler = new Euler(1.0,1.0,0.1,1.5);
System.out.println( "x\t explicit\tactual\t error\t " );
System.out.printf("%f\t%f\t%f\t%f\n", myEuler.getinitialx(),
myEuler.getinitialy(),myEuler.getinitialexact(),
myEuler.getinitialerror());
System.out.printf("my approximated value is %f\n\n",
myEuler.getEulerResult ());
System.out.println("enter another initial value of x: ");
double initialx = input.nextDouble();
System.out.println("enter another initial value of y: ");
double initialy = input.nextDouble();
System.out.println("enter another stepsize value of h: ");
double stepsize = input.nextDouble();
System.out.println("enter another upper bound of x: ");
double finalx1 = input.nextDouble();
myEuler.setEuler(initialx,initialy,stepsize,finalx1);
System.out.println( "x\t explicit\tactual\t error\t " );
System.out.printf("%f\t%f\t%f\t%f\n", myEuler.getinitialx(),
myEuler.getinitialy(),myEuler.getinitialexact(),
myEuler.getinitialerror());
System.out.printf("my approximated value is %f\n\n",
myEuler.getEulerResult ());
}
}
I will be glad if i can en lighted on how to write the java code to collect any ordinary differential equation from the user so as to solve using Euler's method.
What you are looking for is the ability to compile some code at run time, where part of the code is supplied by the user.
There is a package called JOOR that gives you a Reflect class that contains a compile method. The method takes two parameters (a package name:String and the Java code:String).
I've never personally used it, so can not vouch for its robustness, but here is a tutorial and the javadoc:
https://www.jooq.org/products/jOOR/javadoc/latest/org.jooq.joor/org/joor/Reflect.html#compile(java.lang.String,java.lang.String)
https://blog.jooq.org/2018/04/03/how-to-compile-a-class-at-runtime-with-java-8-and-9/
In your case, you would put your user supplied function in place of the following line of code:
return \"Hello World!\";\n"
Beware, you need to be 100% absolutely unconditionally guaranteed that the user can only ever enter a function to be solved. If they are supplying code, remember that unless you take safeguards, the code they enter could very easily be code the removes all of the files on your hard drive (or worse).
For the second part of your question - how do i implement a solution in Java using Euler's method, perhaps check out this link: Euler's Method in java or this https://rosettacode.org/wiki/Euler_method#Java which has it in pretty much every language you can imagine (and probably some you can't).
The error I'm getting is:
"Cannot invoke yearlyPay() on the primitive type double"
I'm trying to call the method: yearlyPay() on the variable calcPay.
I've created yearlyPay() and it looks as so:
public double yearlyPay(double pay)
{
double yearlyPay = hourlyRate * HOURS_YEAR;
System.out.println("public double yearlyPay(double pay): " + yearlyPay);
System.out.println("");
return yearlyPay;
}
then I have another method where calcPay is located
public double localTax(double calcPay)
{
double pay = calcPay;
double localTax;
if (pay.yearlyPay() < 45000)
{
localTax = (1.15 / 100) * pay;
}
else
localTax = (1.15 / 100) * 45000;
return localTax;
}
I also figured that having
double pay = calcPay
is kinda redundant, so I changed it to
public double localTax(double calcPay)
{ //removed double pay = calcPay
double localTax;
if (calcPay.yearlyPay() < 45000)
{
localTax = (1.15 / 100) * pay;
}
else
localTax = (1.15 / 100) * 45000;
return localTax;
}
But...same thing happened.
I googled the problem (with the error message) but I didn't find anything that helped.
There was a place that said to change double to Double, but I didn't know which ones where to change. So I tried each one, one by one...needless to say that didn't work either.
Any help would be appreciated. There is more to the code (which is homework). I didn't post it all cuz I don't think it's useful. Ask if you need specific though.
Also if this question is similar to this one, let me know, I'll delete this and look at that one. I probably missed it in the 3,000,000+ search results on google.
Only objects have methods.
A double is a primitive not an object.
Your yearlyPay() method is a method of the class you are writing, not of double.
So if yearlyPay() is defined in the same class as the call, you call it as:
double n = yearlyPay(calcPay);
... or if you wrote the method in another class (say, PayCalculator):
PayCalculator payCalculator = new PayCalculator();
...
double n = payCalculator.yearlyPay(calcPay);
... or if the method is in PayCalculator as a static method:
double n = PayCalculator.yearlyPay(calcPay);
Incidentally, it's not a good idea to use floating-point number types for money calculations. Google for reasons.
I'm using firebase (android) to store data and I'm saving users like below:
users{
abcdefghi{
name:"abc",
lat:"12.988",
long:-0.123,
desc:"all other desc"
},KLMNGHT{
name:"def",
lat:"11.988",
long:-1.123,
desc:" other desc"
}
}
I want to display all users who comes into my radius zone(proximity zone) which are defined by me according to my location . I am out of ideas . I looked upon Haversine formula. But i don't know to achieve that.
What is the best algorithm to find user?
private const double EARTH_RADIUS = 6378.137;
private static double rad(double d)
{
return d * Math.PI / 180.0;
}
public static double GetDistance(double lat1, double lng1, double lat2, double lng2)
{
double radLat1 = rad(lat1);
double radLat2 = rad(lat2);
double a = radLat1 - radLat2;
double b = rad(lng1) - rad(lng2);
double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a/2),2) +
Math.Cos(radLat1)*Math.Cos(radLat2)*Math.Pow(Math.Sin(b/2),2)));
s = s * EARTH_RADIUS;
s = Math.Round(s * 10000) / 10000;
return s;
}
Maybe this code can help you.
So is the question strictly: given two points on earth A(lan1,lon1) B(lan2,lon2) find the distance between A and B? When you are saying 'best algorithm',do you mean best in terms of development time,time,memory?!
Anyways,assuming 'best' in terms of development time you could use:
1.Google's API explained here: https://developers.google.com/maps/documentation/distance-matrix/intro#DistanceMatrixRequests
2.Here is a simple implementation- but I haven't tested it myself yet-
https://www.geodatasource.com/developers/java
I have to make an implementation to calculate volume of a sphere to be checked with JUnit test, but there are some errors. The formula is correct, but when I test it, it doesn't work :
class VolumeSphere.java
public class VolumeSphere {
public static double volsph(double j) {
double volume;
double const = 1.33;
double phi = 3.14;
volume = const * phi * (j * j * j);
return volume;
}
}
and then this the test file :
VolumeSphereTest.java
import junit.framework.*;
public class VolumeSphereTest extends TestCase {
public VolumeSphereTest(String name) {
super(name);
}
public void testSimple() {
assertEquals(33.4096, VolumeSphere.volsph(2.0));
}
}
when I run the JUnit test, it's said "Expected: (33.4096) but was: (33.4096000005)."
So, what should I do? Thankyou in advance for the help!
The problem is that 33.4096 isn't exactly represented by a double, nor is 1.33, and nor is 3.14. Moreover, the multiplication introduces its own errors. Therefore, the assertEquals needs to be replaced by something that basically means "assert that the value is very close to what we expect".
JUnit has assertEquals(expectedValue, actualValue, errorPermitted) for comparing doubles, which is what you should use here.
In general, double is a poor choice of data type for doing exact arithmetic with numbers expressed as decimals, because it stores binary representations of numbers. If you want accuracy with exact decimals, use BigDecimal instead.
const is a keyword and can't be a name of a variable - pick a different name for your variable.
The problem is that the answer isn't exactly the value you let the JUnit test compare to. The answer is 33.409600000000005 instead of 33.4096. To remedy this, you could use assertEquals(33.4096, VolumeSphere.volsph(2.0), 0.0001);.
This will allow all answers within a difference of 0.0001 around 33.4096. Therefor in this case it will allow 33.4095 to 33.4097.
Also, instead of using double phi = 3.14, you could use Math.PI, which inserts the more significant value of constant pi.
Iam doing a school assignment in Java, and I need some help to do some calculations in a method. Iam used to PHP, and I've appended a lot of my knowledge in the code, but this one I just cant figure out (I know how do do it without the function, but that requires much more lines of code which is stupid).
Here is some of my code:
public static void main (String[] args) {
// User inputs
calculate("Number of beers", 20, 1.50);
}
public static void calculate(String articleName, double numberOfX, double pricePerUnit) {
double subTotal = numberOfX * pricePerUnit;
System.out.printf("%-20s %-1s %10.2f\n", articleName, ":", subTotal);
}
This prints out a nice bill of the things I've bought. Furthermore I would like this method to add the totalprice to a (global?) variable which eventually shows the final price of all items. In PHP i usually wrote a variable named totalDue += subTotal;
Is there any way to do this in java? I would be a shame to write an entire new function to do the math if I just could add the total price of each item into a variable.
Global variables don't exist in Java.
And this is not how it should be done. Rather than the method updating some variable, the method should just return the result of the computation, and the caller should be responsible of using the result as he wants to:
double total = 0D;
total += calculate("Number of beers", 20, 1.50);
total += calculate("Number of pizza", 10, 8);
// ...
This way, you won't have to change anything in the calculate method when you'll want to compute subtotals, or averages, or anything. One method = one responsibility.
This should be true for your PHP programs as well.
After this is done, you should encapsulate the article name, number of items, and unit price in a class, and add methods to the class, like toString (to display the bought item), and computePrice (to compute the price of this bought item).
public static void main (String[] args) {
// User inputs
double total = 0.0;
total += calculate("Number of beers", 20, 1.50);
}
public static double calculate(String articleName, double numberOfX, double pricePerUnit) {
double subTotal = numberOfX * pricePerUnit;
System.out.printf("%-20s %-1s %10.2f\n", articleName, ":", subTotal);
return subTotal;
}