I have the following Mandelbrot set code in C. I am doing the calculation and creating a .ppm file for the final fractal image. The point is that my fractal image is upside down, meaning it is rotated by 90 degrees. You can check it by executing my code:
./mandel > test.ppm
On the other hand, I also want to change the colours. I want to achieve this fractal image:
My final issue is that my code doesn't check the running time of my code. I have the code for this part too, but when code execution finishes it doesn't print the running time. If someone can make the appropriate changes to my code and help me achieve this fractal image, and make elapsed time displayed I would be glad.
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
void color(int red, int green, int blue)
{
fputc((char)red, stdout);
fputc((char)green, stdout);
fputc((char)blue, stdout);
}
int main(int argc, char *argv[])
{
int w = 600, h = 400, x, y;
//each iteration, it calculates: newz = oldz*oldz + p, where p is the current pixel, and oldz stars at the origin
double pr, pi; //real and imaginary part of the pixel p
double newRe, newIm, oldRe, oldIm; //real and imaginary parts of new and old z
double zoom = 1, moveX = -0.5, moveY = 0; //you can change these to zoom and change position
int maxIterations = 1000;//after how much iterations the function should stop
clock_t begin, end;
double time_spent;
printf("P6\n# CREATOR: E.T / mandel program\n");
printf("%d %d\n255\n",w,h);
begin = clock();
//loop through every pixel
for(x = 0; x < w; x++)
for(y = 0; y < h; y++)
{
//calculate the initial real and imaginary part of z, based on the pixel location and zoom and position values
pr = 1.5 * (x - w / 2) / (0.5 * zoom * w) + moveX;
pi = (y - h / 2) / (0.5 * zoom * h) + moveY;
newRe = newIm = oldRe = oldIm = 0; //these should start at 0,0
//"i" will represent the number of iterations
int i;
//start the iteration process
for(i = 0; i < maxIterations; i++)
{
//remember value of previous iteration
oldRe = newRe;
oldIm = newIm;
//the actual iteration, the real and imaginary part are calculated
newRe = oldRe * oldRe - oldIm * oldIm + pr;
newIm = 2 * oldRe * oldIm + pi;
//if the point is outside the circle with radius 2: stop
if((newRe * newRe + newIm * newIm) > 4) break;
}
color(i % 256, 255, 255 * (i < maxIterations));
}
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Elapsed time: %.2lf seconds.\n", time_spent);
return 0;
}
Part 1:
You need to swap the order of your loops to:
for(y = 0; y < h; y++)
for(x = 0; x < w; x++)
That will give you the correctly oriented fractal.
Part 2:
To get the time to print out, you should print it to stderr since you are printing the ppm output to stdout:
fprintf(stderr, "Elapsed time: %.2lf seconds.\n", time_spent);
Part 3:
To get a continuous smooth coloring, you need to use the Normalized Iteration Count method or something similar. Here is a replacement for your coloring section that gives you something similar to what you desire:
if(i == maxIterations)
color(0, 0, 0); // black
else
{
double z = sqrt(newRe * newRe + newIm * newIm);
int brightness = 256. * log2(1.75 + i - log2(log2(z))) / log2(double(maxIterations));
color(brightness, brightness, 255);
}
It isn't quite there because I kind of did a simple approximate implementation of the Normalized Iteration Count method.
It isn't a fully continuous coloring, but it is kind of close.
Related
I have problem I'm sitting with.
For example, suppose someone runs in straight lines and at constant speed between the positions on the left side of Table 1. The time they reach each position is shown next to the position. They stopped running at time 11. If the GPS records a position every 2 units of time, its readings would be the records on the right side of Table 1.
input:
The input consists of a single test case. The first line contains two integers n(2 <= n <= 100) and t(1 <= t <= 100), where n is the total number of positions on the running path, and t is the recording time interval of the GPS (in seconds).
The next n lines contain three integers per line. The i-th line has three integers Xi, yi (-10^6 <= xi, yi <=10^6), and ti (0 <= ti <= 10^6), giving the coordinates of the i-th position on the running path and the time (in seconds) that position is reached. The values of ti’s are strictly increasing. The first and last positions are the start and end of the run. Thus, t1 is always zero.
Given a sequence of positions and times for a running path, as well as the GPS recording time interval , calculate the percentage of the total run distance that is lost by the GPS. Your computations should assume that the runner goes at a constant speed in a straight line between consecutive positions.
My code can calculate the correct output out of the data from the picture but some of the test's will fail. The thing is that I dont now how the tests looks like. So I only know how the indata for the first test looks like.
int main(int arg, char* argv[]) {
int n, t;
int time, new_time, pos_x, pos_y, new_pos_x, new_pos_y;
double run_distance = 0, gps_distance = 0;
int gps_pos_x = 0, gps_pos_y = 0, gps_new_pos_x, gps_new_pos_y;
int gps_time = 0;
if(scanf("%d %d", &n, &t) != 2){
return 0;
}
if(scanf("%d %d %d", &pos_x, &pos_y, &time) != 3){
return 0;
}
for (int i = 0; i < n - 1; i++)
{
if(scanf("%d %d %d", &new_pos_x, &new_pos_y, &new_time) != 3){
return 0;
}
//Calculate run distance
run_distance += sqrt((new_pos_x - pos_x)*(new_pos_x - pos_x) + (new_pos_y - pos_y)*(new_pos_y - pos_y));
//Gps time
gps_time += t;
// Difference between new position X and old position X
int diff = new_pos_x - pos_x;
int pos;
// Difference between gps time and time of old position
int time_diff = gps_time - time;
// Calculate new gps position
pos = diff/(new_time - time) * time_diff + pos_x;
// Save new position
gps_new_pos_x = pos;
// Difference between new position Y and old position Y
diff = new_pos_y - pos_y;
// Calculate new gps position
pos = diff/(new_time - time) * time_diff + pos_y;
// Save new gps position
gps_new_pos_y = pos;
//printf("%d, %d\n", gps_new_pos_x, gps_new_pos_y);
//Calculate gps distance
gps_distance += sqrt((gps_new_pos_x - gps_pos_x)*(gps_new_pos_x - gps_pos_x) + (gps_new_pos_y - gps_pos_y)*(gps_new_pos_y - gps_pos_y));
pos_x = new_pos_x;
pos_y = new_pos_y;
time = new_time;
gps_pos_x = gps_new_pos_x;
gps_pos_y = gps_new_pos_y;
}
gps_distance += sqrt((pos_x - gps_pos_x)*(pos_x - gps_pos_x) + (pos_y - gps_pos_y)*(pos_y - gps_pos_y));
//float diffirence = run_distance - gps_distance;
float value = (run_distance - gps_distance)/run_distance * 100;
printf("%.15f\n", value);
return 0;
}
I am trying to slowly decelerate based on a percentage.
Basically: if percentage is 0 the speed should be speed_max, if the percentage hits 85 the speed should be speed_min, continuing with speed_min until the percentage hits 100%. At percentages between 0% and 85%, the speed should be calculated with the percentage.
I started writing the code already, though I am not sure how to continue:
// Target
int degrees = 90;
// Making sure we're at 0
resetGyro(0);
int speed_max = 450;
int speed_min = 150;
float currentDeg = 0;
float percentage = 0;
while(percentage < 100)
{
//??
getGyroDeg(¤tDeg);
percentage = (degrees/100)*currentDeg;
}
killMotors(1);
Someone in the comments asked why I am doing this.
Unfortunately, I am working with very limited hardware and a pretty bad gyroscope, all while trying to guarantee +- 1 degree precision.
To do this, I am starting at speed_max, slowly decreasing to speed_min (this is to have better control over the motors) when nearing the target value (90).
Why does it stop decelerating at 85%? This is to really be precise and hit the target value successfully.
Assuming speed is linearly calculated based on percentages from 0 to 85 (and stays at speed_min with percentage is gt 85), then this is your formula for calculating speed:
if (percentage >= 85)
{
speed = speed_min;
}
else
{
speed = speed_max - (((speed_max - speed_min)*percentage)/85);
}
Linear interpolation is fairly straight forward.
At percentage 0, the speed should be speed_max.
At percentage 85, the speed should be speed_min.
At percentage values greater than 85, the speed should still be speed_min.
Between 0 and 85, the speed should be linearly interpolated between speed_max and speed_min, so percentage is a 'amount of drop from maximum speed'.
Assuming percentage is of type float:
float speed_from_percentage(float percent)
{
if (percent <= 0.0)
return speed_max;
if (percent >= 85.0)
return speed_min;
return speed_min + (speed_max - speed_min) * (85.0 - percentage) / 85.0;
}
You can also replace the final return with the equivalent:
return speed_max - (speed_max - speed_min) * percentage / 85.0;
If you're truly pedantic, all the constants should be suffixed with F to indicate float and hence use float arithmetic instead of double arithmetic. And hence you should probably also use float for speed_min and speed_max. If everything is meant to be integer arithmetic, you can change float to int and drop the .0 from the expressions.
Assuming getGyroDeg is input from the controller, what you are describing is a proportional control. A constant response curve, ie, 0 to 85 has an output of 450 to 150, and 150 after that, is an ad-hoc approach, based on experience. However, a properly initialised PID controller generally attains a faster time to set-point and greater stability.
#include <stdio.h>
#include <time.h>
#include <assert.h>
#include <stdlib.h>
static float sim_current = 0.0f;
static float sim_dt = 0.01f;
static float sim_speed = 0.0f /* 150.0f */;
static void getGyroDeg(float *const current) {
assert(current);
sim_current += sim_speed * sim_dt;
/* Simulate measurement error. */
*current = sim_current + 3.0 * ((2.0 * rand() / RAND_MAX) - 1.0);
}
static void setGyroSpeed(const float speed) {
assert(speed >= /*150.0f*/-450.0f && speed <= 450.0f);
sim_speed = speed;
}
int main(void) {
/* https://en.wikipedia.org/wiki/PID_controller
u(t) = K_p e(t) + K_i \int_0^t e(\theta)d\theta + K_d de(t)/dt */
const float setpoint = 90.0f;
const float max = 450.0f;
const float min = -450.0f/* 150.0f */;
/* Random value; actually get this number. */
const float dt = 1.0f;
/* Tune these. */
const float kp = 30.0f, ki = 4.0f, kd = 2.0f;
float current, last = 0.0f, integral = 0.0f;
float t = 0.0f;
float e, p, i, d, pid;
size_t count;
for(count = 0; count < 40; count++) {
getGyroDeg(¤t);
e = setpoint - current;
p = kp * e;
i = ki * integral * dt;
d = kd * (e - last) / dt;
last = e;
pid = p + i + d;
if(pid > max) {
pid = max;
} else if(pid < min) {
pid = min;
} else {
integral += e;
}
setGyroSpeed(pid);
printf("%f\t%f\t%f\n", t, sim_current, pid);
t += dt;
}
return EXIT_SUCCESS;
}
Here, instead of the speed linearly decreasing, it calculates the speed in a control loop. However, if the minimum is 150, then it's not going to achieve greater stability; if you go over 90, then you have no way of getting back.
If the controls are [-450, 450], it goes through zero and it is much nicer; I think this might be what you are looking for. It actively corrects for errors.
I am unable to see what I did wrong with my code. I am supposed to determine the trajectory that two cannon shells will take when fired at 500 m/s at an angle of 50 degrees above the horizontal. One of the shells is assumed to experience no drag and the other experiences a drag coefficient of 0.0001. I was wondering as to why my code wasn't plotting correctly. Any help would be great!
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include "philsplot.h"
// Number of shells
#define N 2
// Defining the value of PI
#define PI 3.1415926535
int main()
{
double xmin, xmax, ymin, ymax, theta = (50 * (PI/180));
int color, style;
double expand;
// philsplot function to open an x-window
open_plot("800x600");
int i,j;
double vx[N], vy[N], x[N], y[N], h, ax[N], ay[N];
h = 0.01;
// philsplot function erases the canvas after flushpoint is called
erase_plot();
// plot using km for distance
xmin = 0; xmax = 1;
ymin = 0; ymax = 1;
expand = 1.1;
color = 1;
// philsplot function to set limits of the plotting canvas
box_plot(xmin,xmax,ymin,ymax,expand,color,"Distance (km)","Height (km)","RRRR","TTTT");
// philsplot function that maps the plotting canvas onto the screen
flush_plot();
style = 2;
color = 3;
expand = 1.0;
// The initial values
for(i=0; i<N; i++) {
// want the initial x-position to be this
x[i] = 0;
// want the initial y-position to be this
y[i] = 0;
// want the initial x-velocity to be this
vx[i] = 0.5*cos(theta);
// want the initial y-velocity to be this
vy[i] = 0.5*sin(theta);
}
for(j=0; j<N-1; j++) {
// Using Euler's method you get this:
ax[j] = (-0.0001) * (0.5) * vx[j];
ay[j] = (-0.00981) - (0.0001) * (0.5) * vy[j];
vx[j] = vx[j] - ax[j] * h;
vy[j] = vy[j] - ay[j] * h;
x[j] = x[j] + vx[j] * h;
y[j] = y[j] + vy[j] * h;
putpoint_plot(x[j],y[j],10, style, color, expand, 1);
flush_plot();
delay_plot(1000);
}
printf("hit enter for next plot: ");
getchar();
return 0;
}
How do I create a clean and simple code that creates a circle of point/dots within the larger one? Or something similar (I can't post an image of what I want sorry). I was told to try using a for loop around the outside of my code and have the radius increase slightly each iteration of the loop. However, i don't know how to increase the radius?
This is the code I've been experimenting with so far:
size (400, 400);
background(255);
noStroke();
fill(0);
smooth();
translate(width/2, height/2);
int numpoints = 10;
float angleinc = 2 * PI / numpoints;
int radius = 100;
for (int i = 0; i < numpoints; i++) {
float x = cos(angleinc * i) * radius;
float y = sin(angleinc * i) * radius;
ellipse(x, y, 4, 4);
}
Please, any quick help would be appreciated. Also, I'm fairly new to processing and coding, so I'm not the best...
You'll have better luck if you break your problem down into smaller steps. Step one is creating a function that draws a single "ring" of smaller circles. You already have that step done, all you need to do is separate it into its own function:
void drawCircle(int outerRadius, int innerRadius) {
int numpoints = 10;
float angleinc = 2 * PI / numpoints;
for (int i = 0; i < numpoints; i++) {
float x = cos(angleinc * i) * outerRadius;
float y = sin(angleinc * i) * outerRadius;
ellipse(x, y, innerRadius, innerRadius);
}
}
Then, to draw a set of rings of increasing size, you simply call the function multiple times:
drawCircle(50, 8);
drawCircle(75, 12);
drawCircle(100, 16);
Which you can condense into a for loop:
for(int i = 2; i <= 4; i++){
drawCircle(25*i, 4*i);
}
The whole thing would look something like this:
void setup() {
size (400, 400);
}
void draw() {
background(255);
noStroke();
fill(0);
smooth();
translate(width/2, height/2);
for(int i = 2; i <= 4; i++){
drawCircle(25*i, 4*i);
}
}
void drawCircle(int outerRadius, int innerRadius) {
int numpoints = 10;
float angleinc = 2 * PI / numpoints;
for (int i = 0; i < numpoints; i++) {
float x = cos(angleinc * i) * outerRadius;
float y = sin(angleinc * i) * outerRadius;
ellipse(x, y, innerRadius, innerRadius);
}
}
This is just an example, and you'll have to play around with the numbers to make it look exactly like what you want, but the process is the same: break your problem down into smaller steps, isolate those steps into functions that do one thing, and then call those functions to accomplish your overall goal.
I hope i got your question right-
The formula of a circle around the origin is x=Rcos(angle) y=Rsin(angle) where angel is going between 0 to 2*pi
if you want to draw the circle around point lets say around (x',y'), the formula will be x= x' + Rcos(angle) y= y' + rsin(angle)
The code:
float epsilon = 0.0001f;
float R = 5.5.f;
for (float angle = 0.0; angle < 2*PI; angle += epsilon ) {
float x = x' + R*cos(angle);
float y = y' + R*sin(angle);
drawPoint(x,y);
if( /*condition for changing the radius*/ )
{
R = R*2; // or any change you want to do for R
}
}
It's probably easiest if you use two for loops: one for loop to draw the circle at a certain radius and another for loop which has the previous for loop in it which increases the radius.
int numCircles = 3;
//This for loop increases the radius and draws the circle with another for loop
for (int j = 0; j < numCircles; j++)
{
//This for loop draws the actual circle
for (int i = 0; i < numpoints; i++)
{
float x = cos(angleinc * i) * radius;
float y = sin(angleinc * i) * radius;
ellipse(x, y, 4, 4);
}
//(add code here that increases the radius)
}
I am trying to generate an array of n points that are equidistant from each other and lie on a circle in C. Basically, I need to be able to pass a function the number of points that I would like to generate and get back an array of points.
It's been a really long time since I've done C/C++, so I've had a stab at this more to see how I got on with it, but here's some code that will calculate the points for you. (It's a VS2010 console application)
// CirclePoints.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdio.h"
#include "math.h"
int _tmain()
{
int points = 8;
double radius = 100;
double step = ((3.14159265 * 2) / points);
double x, y, current = 0;
for (int i = 0; i < points; i++)
{
x = sin(current) * radius;
y = cos(current) * radius;
printf("point: %d x:%lf y:%lf\n", i, x, y);
current += step;
}
return 0;
}
Try something like this:
void make_circle(float *output, size_t num, float radius)
{
size_t i;
for(i = 0; i < num; i++)
{
const float angle = 2 * M_PI * i / num;
*output++ = radius * cos(angle);
*output++ = radius * sin(angle);
}
}
This is untested, there might be an off-by-one hiding in the angle step calculation but it should be close.
This assumes I understood the question correctly, of course.
UPDATE: Redid the angle computation to not be incrementing, to reduce float precision loss due to repeated addition.
Here's a solution, somewhat optimized, untested. Error can accumulate, but using double rather than float probably more than makes up for it except with extremely large values of n.
void make_circle(double *dest, size_t n, double r)
{
double x0 = cos(2*M_PI/n), y0 = sin(2*M_PI/n), x=x0, y=y0, tmp;
for (;;) {
*dest++ = r*x;
*dest++ = r*y;
if (!--n) break;
tmp = x*x0 - y*y0;
y = x*y0 + y*x0;
x = tmp;
}
}
You have to solve this in c language:
In an x-y Cartesian coordinate system, the circle with centre coordinates (a, b) and radius r is the set of all points (x, y) such that
(x - a)^2 + (y - b)^2 = r^2
Here's a javascript implementation that also takes an optional center point.
function circlePoints (radius, numPoints, centerX, centerY) {
centerX = centerX || 0;
centerY = centerY || 0;
var
step = (Math.PI * 2) / numPoints,
current = 0,
i = 0,
results = [],
x, y;
for (; i < numPoints; i += 1) {
x = centerX + Math.sin(current) * radius;
y = centerY + Math.cos(current) * radius;
results.push([x,y]);
console.log('point %d # x:%d, y:%d', i, x, y);
current += step;
}
return results;
}