Calculation exponential growth with recursion - recursion

So I'm trying to figure out how to calculate a stock's exponential growth with recursion. The stock's original value, the percentage and the number of years is given by the user.
This is what I thought would work but I was proven wrong. Any ideas?
public static void main(String[] args) {
String cheese = JOptionPane.showInputDialog("Stock price.");
double v = Double.parseDouble(cheese);
String mayo = JOptionPane.showInputDialog("Percentage.");
double p = Double.parseDouble(mayo);
String ham = JOptionPane.showInputDialog("Years.");
double n = Double.parseDouble(ham);
System.out.println(stockGrowth(v, p, n));
}
static double stockGrowth(double v, double p, double n) {
if (n > 0) {
return stockGrowth(v * Math.pow(p, n)) + Math.pow(p, n - 1);
} else {
return v;
}
}
Cheers.

If p=0.05 (that is 5%) then one year later v has grown to v*1.05 = v*(1+p).
This leads to the following definition:
static double stockGrowth(double v, double p, double n) {
if (n > 0) {
return stockGrowth(v * (1+p), p, n - 1);
} else {
return v;
}
}

Related

Trying to implement a maths equation in a method

Code a method called calcSeries that calculates and returns the value of y in the following series:
y=1+∑ni=1i2i∗x
where n and x are two input integers and y is the returned double value.
Example:
Input: x=8, n=4
So, the series is y=1+1/(1∗8)+2^2/(2∗8)+3^2/(3∗8)+4^2/(4∗8)
Output: 2.25
I am having trouble with going about how to design the code. So far I have:
public double calcSeries(int n, int x){
double y = 0.0;
int a = 1;
double b = Math.pow(n,2)/(n*x);
for (int i = 1; i < (n + 1); i++) {
}
return y;
}
You've already written most of it. Just added the declaration of b inside the loop, since it's value depends on the current i.
public double calcSeries(int n, int x){
double y = 1.0;
for (int i = 1; i < (n + 1); i++) {
double b = Math.pow(i,2)/(i*x);
y += b;
}
return y;
}

Calculate sound value with distance

I have a more mathematical than programming question, sorry if I'm not in the right section. In my 2D game, we can move the camera on a map where there are objects that can emit sound, and this sound volume (defined by a float from 0 to 1) must increase when the screen center is near this object. For example, when the object is at the screen center, the sound volume is 1, and when we move away, the volume must decrease. Each object has its own scope value. (for example 1000 pixels).
I don't know how to write a method that can calculate it.
Here is some of my code (which is not the right calculation) :
private function setVolumeWithDistance():Void
{
sound.volume = getDistanceFromScreenCenter() / range;
// So the volume is a 0 to 1 float, the range is the scope in pixels and
// and the getDistanceFromScreenCenter() is the distance in pixels
}
I already have the method which calculates the distance of the object from the center screen :
public function getDistanceFromScreenCenter():Float
{
return Math.sqrt(Math.pow((Cameraman.getInstance().getFocusPosition().x - position.x), 2) +
Math.pow((Cameraman.getInstance().getFocusPosition().y - position.y), 2));
Simple acoustics can help.
Here is the formula for sound intensity from a point source. It follows an inverse square of distance rule. Build that into your code.
You need to consider the mapping between global and screen coordinates. You have to map pixel location on the screen to physical coordinates and back.
Your distance code is flawed. No one should use pow() to square numbers. Yours is susceptible to round off errors.
This code combines the distance calculation, done properly, and attempts to solve the inverse square intensity calculation. Note: Inverse square is singular for zero distance.
package physics;
/**
* Simple model for an acoustic point source
* Created by Michael
* Creation date 1/16/2016.
* #link https://stackoverflow.com/questions/34827629/calculate-sound-value-with-distance/34828300?noredirect=1#comment57399595_34828300
*/
public class AcousticPointSource {
// Units matter here....
private static final double DEFAULT_REFERENCE_INTENSITY = 0.01;
private static final double DEFAULT_REFERENCE_DISTANCE = 1.0;
// Units matter here...
private double referenceDistance;
private double referenceIntensity;
public static void main(String[] args) {
int numPoints = 20;
double x = 0.0;
double dx = 0.05;
AcousticPointSource source = new AcousticPointSource();
for (int i = 0; i < numPoints; ++i) {
x += dx;
Point p = new Point(x);
System.out.println(String.format("point %s intensity %-10.6f", p, source.intensity(p)));
}
}
public AcousticPointSource() {
this(DEFAULT_REFERENCE_DISTANCE, DEFAULT_REFERENCE_INTENSITY);
}
public AcousticPointSource(double referenceDistance, double referenceIntensity) {
if (referenceDistance <= 0.0) throw new IllegalArgumentException("distance must be positive");
if (referenceIntensity <= 0.0) throw new IllegalArgumentException("intensity must be positive");
this.referenceDistance = referenceDistance;
this.referenceIntensity = referenceIntensity;
}
public double distance2D(Point p1) {
return distance2D(p1, Point.ZERO);
}
public double distance2D(Point p1, Point p2) {
double distance = 0.0;
if ((p1 != null) && (p2 != null)) {
double dx = Math.abs(p1.x - p2.x);
double dy = Math.abs(p1.y - p2.y);
double ratio;
if (dx > dy) {
ratio = dy/dx;
distance = dx;
} else {
ratio = dx/dy;
distance = dy;
}
distance *= Math.sqrt(1.0 + ratio*ratio);
if (Double.isNaN(distance)) {
distance = 0.0;
}
}
return distance;
}
public double intensity(Point p) {
double intensity = 0.0;
if (p != null) {
double distance = distance2D(p);
if (distance != 0.0) {
double ratio = this.referenceDistance/distance;
intensity = this.referenceIntensity*ratio*ratio;
}
}
return intensity;
}
}
class Point {
public static final Point ZERO = new Point(0.0, 0.0, 0.0);
public final double x;
public final double y;
public final double z;
public Point(double x) {
this(x, 0.0, 0.0);
}
public Point(double x, double y) {
this(x, y, 0.0);
}
public Point(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
#Override
public String toString() {
return String.format("(%-10.4f,%-10.4f,%-10.4f)", x, y, z);
}
}

sequence of numbers using recursion

I want to compute sequence of numbers like this:
n*(n-1)+n*(n-1)*(n-2)+n*(n-1)*(n-2)*(n-3)+n*(n-1)*(n-2)*(n-3)*(n-4)+...+n(n-1)...(n-n)
For example n=5 and sum equals 320.
I have a function, which compute one element:
int fac(int n, int s)
{
if (n > s)
return n*fac(n - 1, s);
return 1;
}
Recomputing the factorial for each summand is quite wasteful. Instead, I'd suggest to use memoization. If you reorder
n*(n-1) + n*(n-1)*(n-2) + n*(n-1)*(n-2)*(n-3) + n*(n-1)*(n-2)*(n-3)*...*1
you get
n*(n-1)*(n-2)*(n-3)*...*1 + n*(n-1)*(n-2)*(n-3) + n*(n-1)*(n-2) + n*(n-1)
Notice how you start with the product of 1..n, then you add the product of 1..n divided by 1, then you add the product divided by 1*2 etc.
I think a much more efficient definition of your function is (in Python):
def f(n):
p = product(range(1, n+1))
sum_ = p
for i in range(1, n-1):
p /= i
sum_ += p
return sum_
A recursive version of this definition is:
def f(n):
def go(sum_, i):
if i >= n-1:
return sum_
return sum_ + go(sum_ / i, i+1)
return go(product(range(1, n+1)), 1)
Last but not least, you can also define the function without any explicit recursion by using reduce to generate the list of summands (this is a more 'functional' -- as in functional programming -- style):
def f(n):
summands, _ = reduce(lambda (lst, p), i: (lst + [p], p / i),
range(1, n),
([], product(range(1, n+1))))
return sum(summands)
This style is very concise in functional programming languages such as Haskell; Haskell has a function call scanl which simplifies generating the summands so that the definition is just:
f n = sum $ scanl (/) (product [1..n]) [1..(n-2)]
Something like this?
function fac(int n, int s)
{
if (n >= s)
return n * fac(n - 1, s);
return 1;
}
int sum = 0;
int s = 4;
n = 5;
while(s > 0)
{
sum += fac(n, s);
s--;
}
print sum; //320
Loop-free version:
int fac(int n, int s)
{
if (n >= s)
return n * fac(n - 1, s);
return 1;
}
int compute(int n, int s, int sum = 0)
{
if(s > 0)
return compute(n, s - 1, sum + fac(n, s));
return sum;
}
print compute(5, 4); //320
Ok ther is not mutch to write. I would suggest 2 methodes if you want to solve this recursiv. (Becaus of the recrusiv faculty the complexity is a mess and runtime will increase drasticaly with big numbers!)
int func(int n){
return func(n, 2);
}
int func(int n, int i){
if (i < n){
return n*(fac(n-1,n-i)+func(n, i + 1));
}else return 0;
}
int fac(int i,int a){
if(i>a){
return i*fac(i-1, a);
}else return 1;
}

Finding an error in hash function when resizing table

While preparing for an exam I came across a question about hash tables.
I am given a table of length 11 with the following hash function:
h(k,i) = ( k mod 13 + i * (1 + k mod 7) ) mod 11
The hash table is then resized to size 12. So the new hash function becomes:
h'(k,i) = ( k mod 13 + i * (1 + k mod 7) ) mod 12
Which problems occur?
The problem is that the hash function becomes worse.
In the first case, the distribution of different combinations of k and i is very even among the 11 hash bins. In the second case, the distribution is not so even - particularly, the number of combinations of k and i for which the result of the hash function will be 0 is noticably higher.
Of course, during an exam, one would probably have to argue why it is this way. It's somehow related to
k mod 13 being a value between 0 and 12
k mod 7 being a value between 0 and 6 (which divides 12)
maybe, somehow: 11 is a prime number and 12 has many divisors...
but (at least for me) it is hard to find a convincing reasoning that goes beyond these trivial insights. Maybe you have another idea based on that.
import java.util.LinkedHashMap;
import java.util.Map;
public class HashTest
{
public static void main(String[] args)
{
int maxK = 30;
int maxI = 30;
System.out.println(computeFrequencies(h0, maxK, maxI));
System.out.println(computeFrequencies(h1, maxK, maxI));
}
private static Map<Integer, Integer> computeFrequencies(
Hash hash, int maxK, int maxI)
{
Map<Integer, Integer> frequencies =
new LinkedHashMap<Integer, Integer>();
for (int k=0; k<maxK; k++)
{
for (int i=0; i<maxI; i++)
{
int value = hash.compute(k, i);
Integer count = frequencies.get(value);
if (count == null)
{
count = 0;
}
frequencies.put(value, count+1);
}
}
return frequencies;
}
private static interface Hash
{
int compute(int k, int i);
}
private static final Hash h0 = new Hash()
{
#Override
public int compute(int k, int i)
{
return ((k % 13) + i * (1 + (k % 7))) % 11;
}
};
private static final Hash h1 = new Hash()
{
#Override
public int compute(int k, int i)
{
return ((k % 13) + i * (1 + (k % 7))) % 12;
}
};
}

Calculating Standard Deviation in Assignment

I have an assignment for my class that reads like this: Write a class called Stats. The constructor will take no input. There will be a method addData(double a) which will be used to add a value from the test program. Methods getCount(), getAverage() and getStandardDeviation() will return the appropriate values as doubles.
Here's what I have so far:
public class Stats
{
public Stats (double a)
{
a=0.0
}
public void addData(double a)
{
while (
sum=sum+a;
sumsq=sumsq+Math.pow(a,2)
count=count+1
}
public double getCount()
{
return count;
}
public double getAverage()
{
average=sum/count
return average;
}
public double getStandardDeviation()
{
private double sum=o;
private double count=0;
private double sumsq=0;
My problem is figuring out how to calculate the standard deviation using the variables I've defined.
Thanks guys!
You can't do this with the variables you defined. You need to keep the original data to be able to compute the formula
sigma = Math.sqrt( sum(Math.pow(x-mean, 2)) / count )
So,
(1) create private array or list into which you'll add your values in addData. That's all you need to do in addData.
(2) getCount = length of the list
(3) getAverage = sum of values in list / getCount()
(4) getStandardDeviation is something like
double avg = getAverage();
double cnt = getCount();
double sumsq = 0;
for (int i = 0; i < values.Count(); i++) {
sumsq += Math.pow(values[i] - avg, 2);
}
stdev = Math.sqrt(sumsq / cnt);

Resources