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;
}
Related
im trying to solve a differentiel delay equation system with c++. Im a newbie in terms of coding, so please if you have recommendations, tell me, I would like to improve my writing! What i want to do: initialize the history-array and then start to solve the differential equation by overwriting the history-array. But the problem is, I get the error message:
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 9999) >= this->size() (which is 9999)
It seems that the history-arrays are out of range. I tried to put a std::cout in after the second if-condition to check if the code is going through the second for-loop, but he isn't. Since im learning c++ by doing right now, the problem isn't really clear to me. I hope someone sees the error. And dont hesitate to improve my code, I would really appreciate!
Thanks for your help!
#include <iostream>
#include <vector>
#include <cmath>
#include <iomanip>
#include <fstream>
const double pi = 3.14159265358979323846;
//delay
int tau = 1;
//initial values
double x = 1.0;
double y = 1.0;
double t = 0.0;
//constants and parameters
double K = 0.25;
double lam = 0.5;
double omega = pi;
double dx, dy;
//step-size
double dt = pow(10.0, -4.0);
//number of steps
int Delta = static_cast<int>(tau/dt);
std::vector<double> hist_x((static_cast<int>(tau/dt) - 1), 0.0);
std::vector<double> hist_y((static_cast<int>(tau/dt) - 1), 0.0);
std::vector<double> t_val;
std::vector<double> x_val;
std::vector<double> y_val;
double euler(double f, double di, double time_step){
f = f + time_step * di;
return f;
}
int main()
{
std::ofstream file_x;
std::ofstream file_y;
std::ofstream file_t;
file_x.open("x_val.txt");
file_y.open("y_val.txt");
file_t.open("t_val.txt");
for(int n = 0; n < 2; n++){
if(n==0){
for(int j; j < Delta; j++){
dx = lam * x + omega * x;
dy = lam * y - omega * x;
x = euler(x, dx, dt);
y = euler(y, dy, dt);
t = t + dt;
x_val.push_back(x);
y_val.push_back(y);
t_val.push_back(t);
hist_x.at(j) = x;
hist_y.at(j) = y;
file_x<<x_val.at(j)<<std::endl;
file_y<<y_val.at(j)<<std::endl;
file_t<<t_val.at(j)<<std::endl;
}
}
if(!(n==0)){
for(int k = 0; k < Delta; k++){
//f1(x,y)
dx = lam * x + omega * x - K * ( x - hist_x.at(k) );
//f2(x,y)
dy = lam * y - omega * x - K * ( y - hist_y.at(k) );
x = euler(x, dx, dt);
y = euler(y, dy, dt);
t = t + dt;
x_val.push_back(x);
y_val.push_back(y);
t_val.push_back(t);
hist_x.at(k) = x;
hist_y.at(k) = y;
file_x<<x_val.at(k + n * Delta)<<std::endl;
file_y<<y_val.at(k + n * Delta)<<std::endl;
file_t<<t_val.at(k + n * Delta)<<std::endl;
}
}
}
file_x.close();
file_y.close();
file_t.close();
}
for(int j; j < Delta; j++){
You forgot to initialize j; you meant:
for (int j = 0; j < Delta; j++)
{
int Delta = static_cast<int>(tau/dt);
std::vector<double> hist_x((static_cast<int>(tau/dt) - 1), 0.0);
std::vector<double> hist_y((static_cast<int>(tau/dt) - 1), 0.0);
You index from 0 to Delta−1, this means the vectors need to have Delta elements, and you allocate one less; correct:
std::vector<double> hist_x(Delta, 0.0);
std::vector<double> hist_y(Delta, 0.0);
vector<vector<int>> arr{
{1,2},
{2,3},
{4,5},
{1,5}
};
vector<vector<int>> adj( m , vector<int> (m, 0));
for (int i = 0; i < arr.size(); i++) {
// Find X and Y of Edges
int x = arr[i][0];
int y = arr[i][1];
// Update value to 1
adj[x][y] = 1;
adj[y][x] = 1;
}
I am trying to update the vector of vector value using the above code but I am getting a segmentation error. How can I change the element value of the 2D vector of a particular location.
I am trying to code in R a(centered) weighted moving average function that returns me a vector of the same size than the input vector.
The following code almost gives me what I want but it does not work for the first and last values of my vector
set.seed(0)
len=10
x=floor(l*runif(l))
weights=c(1,3,0,3,1)
weights=weights/sum(weights)
rollapply(x,width=length(weights), function(x) sum(x*weights),align="center")
na.omit(filter(x,sides=2,weights))
Setting partial=TRUE in the rollapply function is sort of what I want to do. Anyway it does not work since my function does not support an x of changing sizes.
I could the latter and manually add the sides computations with a loop. It would work but I would like to find a nicer (computationally faster) way to do it.
For a more rigorous description of my needs here is a mathematical version
r is the vector my function would return
x and the weights w as inputs :
With Rcpp, you can do:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector roll_mean(const NumericVector& x,
const NumericVector& w) {
int n = x.size();
int w_size = w.size();
int size = (w_size - 1) / 2;
NumericVector res(n);
int i, ind_x, ind_w;
double w_sum = Rcpp::sum(w), tmp_wsum, tmp_xwsum, tmp_w;
// beginning
for (i = 0; i < size; i++) {
tmp_xwsum = tmp_wsum = 0;
for (ind_x = i + size, ind_w = w_size - 1; ind_x >= 0; ind_x--, ind_w--) {
tmp_w = w[ind_w];
tmp_wsum += tmp_w;
tmp_xwsum += x[ind_x] * tmp_w;
}
res[i] = tmp_xwsum / tmp_wsum;
}
// middle
int lim2 = n - size;
for (; i < lim2; i++) {
tmp_xwsum = 0;
for (ind_x = i - size, ind_w = 0; ind_w < w_size; ind_x++, ind_w++) {
tmp_xwsum += x[ind_x] * w[ind_w];
}
res[i] = tmp_xwsum / w_sum;
}
// end
for (; i < n; i++) {
tmp_xwsum = tmp_wsum = 0;
for (ind_x = i - size, ind_w = 0; ind_x < n; ind_x++, ind_w++) {
tmp_w = w[ind_w];
tmp_wsum += tmp_w;
tmp_xwsum += x[ind_x] * tmp_w;
}
res[i] = tmp_xwsum / tmp_wsum;
}
return res;
}
I use this function in one of my packages.
Just put that in a .cpp file and source it with Rcpp::sourceCpp.
I'm trying to implement a recursive quicksort in C that does all swapping by using bitwise XOR operations. Here is what I've got so far:
//bitwise recursive quicksort
void quicksort(int *int_array,int p, int r){
if(p<r){
int q = part(int_array, p, r);
quicksort(int_array,p, q-1);
quicksort(int_array, q+1, r);
}
}
//Partition
int part(int *int_array, int p, int r){
int pivot = int_array[r];
int i = p-1;
int j;
for(j = p; j<=r-1; j++){
if(int_array[j] <= pivot){
i++;
int_array[i] = int_array[i] ^ int_array[j];
int_array[j] = int_array[i] ^ int_array[j];
int_array[i] = int_array[i] ^ int_array[j];
}
}
int_array[i+1] = int_array[i+1] ^ int_array[r];
int_array[r] = int_array[i+1] ^ int_array[r];
int_array[i+1] = int_array[i+1] ^ int_array[r];
return i+1;
}
When I run this code on an array of 20 ints, 19 out of 20 of them get changed to 0. Any idea why? I can't see anything wrong with the XOR swapping. Any help appreciated, thanks!
The XOR swap algorithm doesn't work when swapping an item with itself, because any number XORed with itself will be 0, the algorithm relies on there being two locations. So after the first line you have just wiped the value.
XOR swap algorithm:
However, the algorithm fails if x and y use the same storage location, since the value stored in that location will be zeroed out by the first XOR instruction, and then remain zero; it will not be "swapped with itself". Note that this is not the same as if x and y have the same values. The trouble only comes when x and y use the same storage location, in which case their values must already be equal.
You can just put a test around your swaps to make sure you never try swapping an element with itself:
int part(int *int_array, int p, int r){
int pivot = int_array[r];
int i = p-1;
int j;
for(j = p; j<=r-1; j++){
if(int_array[j] <= pivot){
i++;
if(i != j) // avoid XORing item with itself
{
int_array[i] = int_array[i] ^ int_array[j];
int_array[j] = int_array[i] ^ int_array[j];
int_array[i] = int_array[i] ^ int_array[j];
}
}
}
if(i+1 != r) // avoid XORing item with itself
{
int_array[i+1] = int_array[i+1] ^ int_array[r];
int_array[r] = int_array[i+1] ^ int_array[r];
int_array[i+1] = int_array[i+1] ^ int_array[r];
}
return i+1;
}
Ok so I found this article and I am confused by some parts of it. If anyone can explain this process in more depth to me I would greatly appreciate it because I have been trying to code this for 2 months now and still have not gotten a correct version working yet. I am specifically confused about the Persistence part of the article because I mostly do not understand what the author is trying to explain about it and at the bottom of the article he talks about a 2D pseudo code implementation of this but the PerlinNoise_2D function does not make sense to me because after the random value is smoothed and interpolated, it is an integer value but the function takes float values? Underneath the persistence portion there is the octaves part. I do not quite understand because he "adds" the smoothed functions together to get the Perlin function. What does he mean by"adds" because you obviously do not add the values together. So if anyone can explain these parts to me I would be very happy. Thanks.
Here is my code:
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class TerrainGen extends JPanel {
public static int layers = 3;
public static float[][][][] noise = new float[16][16][81][layers];
public static int[][][][] octaves = new int[16][16][81][layers];
public static int[][][][] perlin = new int[16][16][81][layers];
public static int[][][] perlinnoise = new int[16][16][81];
public static int SmoothAmount = 3;
public static int interpolate1 = 0;
public static int interpolate2 = 10;
public static double persistence = 0.25;
//generate noise
//smooth noise
//interpolate noise
//perlin equation
public TerrainGen() {
for(int t = 0; t < layers; t++) {
for(int z = 0; z < 81; z++) {
for(int y = 0; y < 16; y++) {
for(int x = 0; x < 16; x++) {
noise[x][y][z][t] = GenerateNoise();
}
}
}
}
for(int t = 0; t < layers; t++) {
SmoothNoise(t);
}
for(int t = 0; t < layers; t++) {
for(int z = 0; z < 81; z++) {
for(int y = 0; y < 16; y++) {
for(int x = 0; x < 16; x++) {
octaves[x][y][z][t] = InterpolateNoise(interpolate1, interpolate2, noise[x][y][z][t]);
}
}
}
}
for(int t = 0; t < layers; t++) {
PerlinNoise(t);
}
}
public static Random generation = new Random(5);
public float GenerateNoise() {
float i = generation.nextFloat();
return i;
}
public void SmoothNoise(int t) {
//Huge smoothing algorithm
}
//Cosine interpolation
public int InterpolateNoise(int base, int top, float input) {
return (int) ((1 - ((1 - Math.cos(input * 3.1415927)) * 0.5)) + top * ((1 - Math.cos(input * 3.1415927)) * 0.5));
}
public void PerlinNoise(int t) {
double f = Math.pow(2.0, new Double(t));
double a = Math.pow(persistence, new Double(t));
for(int z = 0; z < 81; z++) {
for(int y = 0; y < 16; y++) {
for(int x = 0; x < 16; x++) {
perlin[x][y][z][t] = (int) ((octaves[x][y][z][t] * f) * a);
}
}
}
}
public static void main(String [] args) {
JFrame frame = new JFrame();
frame.setSize(180, 180);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TerrainGen test = new TerrainGen();
frame.add(test);
frame.setVisible(true);
}
public static int size = 5;
public void paintComponent(Graphics g) {
super.paintComponent(g);
int i = 0;
for(int t = 0; t < 9; t++) {
for(int z = 0; z < 9; z++) {
for(int y = 0; y < 16; y++) {
for(int x = 0; x < 16; x++) {
g.setColor(new Color(perlin[x][y][i][0] * 10, perlin[x][y][i][0] * 10, perlin[x][y][i][0] * 10));
g.fillRect((z * (16 * size)) + (x * size), (t * (16 * size)) + (y * size), size, size);
}
}
i++;
}
}
repaint();
}
}
And I did not include the smoothing part because that was about 400 lines of code to smooth between chunks.
What the article calls persistence is how the amplitude of the higher frequency noises "falls off" when they are combined.
"octaves" are just what the article calls the noise functions at different frequencies.
You take 1.0 and repeatedly multiply by the persistence to get the list of amplitudes to multiply each octave by - e.g. a persistence of 0.8 gives factors 1.0, 0.8, 0.64, 0.512.
The noise is not an integer, his function Noise1 produces noise in the range 0..1 - i.e. variable n is an Int32 bit it returns a float.
The input paramters are integers i.e. The Noise1 function is only evaluated at (1, 0) or (2, 2).
After smoothing/smearing the noise a bit in SmoothNoise_1 the values get interpolated to produce the values inbetween.
Hope that helped!!
this loop makes octaves from 2d noise. same loop would work for 3d perlin...
function octaves( vtx: Vector3 ): float
{
var total = 0.0;
for (var i:int = 1; i < 7; i ++)//num octaves
{
total+= PerlinNoise(Vector3 (vtx.x*(i*i),0.0,vtx.z*(i*i)))/(i*i);
}
return total;//added multiple perlins into noise with 1/2/4/8 etc ratios
}
the best thing i have seen for learning perlin is the following code. instead of hash tables, it uses sin based semi random function. using 2-3 octaves it becomes high quality perlin... the amazing thing is that i ran 30 octave of this on a realtime landscape and it didnt slow down, whereas i used 1 voronoi once and it was slowing. so... amazing code to learn from.
#ifndef __noise_hlsl_
#define __noise_hlsl_
// hash based 3d value noise
// function taken from https://www.shadertoy.com/view/XslGRr
// Created by inigo quilez - iq/2013
// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
// ported from GLSL to HLSL
float hash( float n )
{
return frac(sin(n)*43758.5453);
}
float noise( float3 x )
{
// The noise function returns a value in the range -1.0f -> 1.0f
float3 p = floor(x);
float3 f = frac(x);
f = f*f*(3.0-2.0*f);
float n = p.x + p.y*57.0 + 113.0*p.z;
return lerp(lerp(lerp( hash(n+0.0), hash(n+1.0),f.x),
lerp( hash(n+57.0), hash(n+58.0),f.x),f.y),
lerp(lerp( hash(n+113.0), hash(n+114.0),f.x),
lerp( hash(n+170.0), hash(n+171.0),f.x),f.y),f.z);
}
note that sin is expensive on CPU, instead you would use:
function hash ( n: float ): float
{//random -1, 1
var e = ( n *73.9543)%1;
return (e*e*142.05432)%2-1;// fast cpu random by me :) uses e*e rather than sin
}