Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Does this make any sense?
I got stuck in here with 4 errors and it is because I didn't declared the ints q,d,n,p. But if I do so it'll keep sending me more errors.
There might be something about having mixed ints and floats.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
{
printf("O hai! ");
}
float valueTotal, quarter, valueQuarter, dime, valueDime,nickel, valueNickel, penny, valuePenny;
do
{
printf("How much change is owed?\n");
valueTotal = GetFloat();
}
while (valueTotal <= 0);
for (float quarter = 0; valueTotal >= 0.25; quarter--)
{
valueQuarter = valueTotal - ( q * 0.25);
}
for (float dime = 0; valueQuarter >= 0.10; dime--)
{
valueDime = valueQuarter - ( d * 0.10);
}
for (float nickel = 0; valueDime >= 0.05; nickel--)
{
valueNickel = valueDime - ( n * 0.05);
}
for (float penny = 0; valueNickel >= 0.01; penny--)
{
valuePenny = valueNickel - ( p * 0.01);
}
printf("q+d+n+p\n");
}
I didn't declared the ints q,d,n,p.
This is exactly your problem - at least one of them, anyways. If these variables are undeclared, how in the world is the program/code supposed to evaluate something like q * 0.25 ? If I said "Hey man, what is x times 0.25?" You'd have absolutely no idea, or tell me that the answer depends on x. The same goes with this code.
You said:
But if I do so it'll keep sending me more errors.
I'm assuming you also need to initialize them (or, in layman's terms, set them equal to something ie. q = 0)
Also, none of your loop conditions are actually changing.... meaning they're infinitely looping. Make sure that the code inside your loop is actually helping you reach the goal of satisfying the loop condition; for example:
for (float quarter = 0; valueTotal >= 0.25; quarter--)
{
valueQuarter = valueTotal - ( q * 0.25);
}
valueTotal is ALWAYS going to be greater than 0.25 (if it is less than 0.25 to begin with) since you are never changing it at all.
Related
I want to write an audio code in c++ for my microcontroller-based synthesizer which should allow me to generate a sampled square wave signal using the Fourier Series equation.
My question in general is: is there a way to set an "unknown" variable like "x" inside a sine-equation, and change its value afterwards?
What do I mean by that:
If you take a look on my code i've written so far you see the following:
void SquareWave(int mHarmonics){
char x;
for(int k = 0; k <= mHarmonics; k++){
mFourier += 1/((2*k)+1)*sin(((2*k)+1)*2*M_PI*x/SAMPLES_TOTAL);
}
for(x = (int)0; x < SAMPLES_TOTAL; x++){
mWave[x] = mFourier;
}
}
Inside the first for loop mFourier is summing weighted sinus-signals dependent by the number of Harmonics "mHarmonics". So a note on my keyboard should be setting up the harmonic spectrum automatically.
In this equation I've set x as a character and now we get to the center of my problem because i want to set x as a "unknown" variable which has a value that i want to set afterwards and if x would be an integer it would have some standard value like 0, which would make the whole equation incorrect.
In the bottom loop i want to write this Fourier Series sum inside an array mWave, which will be the resulting output. Is there a possibility to give the sum to mWave[x], where x is a "unknown" multiplier inside the sine signal first, and then change its values afterwards inside the second loop?
Sorry if this is a stupid question, I have not much experience with c++ but I try to learn it by making these stupid mistakes!
Cheers
#Useless told you what to do, but I am going to try to spell it out for you.
This is how I would do it:
#include <vector>
/**
* Perform a rectangular window in the frequency domain of a time domain square
* wave. This should be a sync impulse response.
*
* #param x The time domain sample within the period of the signal.
* #param harmonic_count The number of harmonics to aggregate in the result.
* #param sample_count The number of samples across the square wave period.
*
* #return double The time domain result of the combined harmonics at point x.
*/
double box_car(unsigned int x,
unsigned int harmonic_count,
unsigned int sample_count)
{
double mFourier = 0.0;
for (int k = 0; k <= harmonic_count; k++)
{
mFourier += 1.0 / ((2 * k) + 1) * sin(((2 * k) + 1) * 2.0 * M_PI * x / sample_count);
}
return mFourier;
}
/**
* Calculate the suqare wave samples across the time domain where the samples
* are filtered to only include the harmonic_count.
*
* #param harmonic_count The number of harmonics to aggregate in the result.
* #param sample_count The number of samples across the square wave period.
*
* #return std::vector<double>
*/
std::vector<double> box_car_samples(unsigned int harmonic_count,
unsigned int sample_count)
{
std::vector<double> square_wave;
for (unsigned int x = 0; x < sample_count; x++)
{
double sample = box_car(x, harmonic_count, sample_count);
square_wave.push_back(sample);
}
return square_wave;
}
So mWave[x] is returned as a std::vector of doubles (floating point).
The function box_car_samples() is f(k, x) as stated before.
So since I can't use vectors inside Arduino IDE anyhow I've tried the following solution:
...
void ComputeBandlimitedSquareWave(int mHarmonics){
for(int i = 0; i < sample_count; i++){
mWavetable[i] = ComputeFourierSeriesSquare(x);
if (x < sample_count) x++;
}
}
float ComputeFourierSeriesSquare(int x){
for(int k = 0; k <= mHarmonics; k++){
mFourier += 1/((2*k)+1)*sin(((2*k)+1)*2*M_PI*x/sample_count);
return mFourier;
}
}
...
First I thought this must be right a minute ago, but my monitors prove me wrong...
It sounds like a completely messed up sum of signals first, but after about 2 seconds the true characterisic squarewave sound comes through. I try to figure out what I'm overseeing and keep You guys updated if I can isolate that last part coming through my speakers, because it actually has a really decent sound. Only the messy overlays in the beginning are making me desperate right now...
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
you might remember me or running a kind of a 'Lightroom' panel, using C++ and Qt for GUI.
Today I was reading about implementing a unit testing for my main classes, but my question is, how can I test a function that does not return anything?
for example, I got that function:
void ImgProcessing::processMaster(cv::Mat& img, cv::Mat& tmp, int brightness, int red, int green, int blue, double contrast){
for(int i = 0; i < img.rows; i++)
for(int j = 0; j < img.cols; j++)
for(int k = 0; k < 3; k++){
if(k == 0) //_R
tmp.at<cv::Vec3b>(i,j)[k] = cv::saturate_cast<uchar>((img.at<cv::Vec3b>(i,j)[k] + brightness + red )*(259 * (contrast + 255) / (255 * (259 - contrast))));
if(k == 1) //_G
tmp.at<cv::Vec3b>(i,j)[k] = cv::saturate_cast<uchar>((img.at<cv::Vec3b>(i,j)[k] + brightness + green )*(259 * (contrast + 255) / (255 * (259 - contrast))));
if(k == 2) //_B
tmp.at<cv::Vec3b>(i,j)[k] = cv::saturate_cast<uchar>((img.at<cv::Vec3b>(i,j)[k] + brightness + blue )*(259 * (contrast + 255) / (255 * (259 - contrast))));
}
this function just take the obj 'mat img', and modify the 'mat tmp' obj.
than I update the UI for display the modified image, by using another dedicated function in my gui class.
Has someone already encounter something like that?
It does not make a difference if it returns a value the regular way or via an output parameter. The procedure is the same anyway. Run the function and check that the output parameter has the expected value.
This is C code, but it does not make a difference for understanding the concept. Consider these functions:
int addOne1(int x) { return x+1; }
void addOne2(int x, int* ret) { *ret = x+1; }
These can now be tested in this way:
const int x = 3;
int ret1, ret2;
ret1 = addOne1(x);
addOne2(x, &ret2);
assert(ret1 == 4);
assert(ret2 == 4);
If the output parameter also is an input parameter, then you of course need to make sure that you know the initial value.
void inc(int *x) { (*x)++; }
int x=3;
inc(&x);
assert(x == 4);
Technically, modifying a parameter IS considered a side effect. But as long as you are careful it's not a big issue. The difference compared to using a member variable is huge. And if you start modifying globals you will soon make it REALLY hard to test the code.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am attempting to create a device that talks to a Casio fx-9750 calculator through its serial port with an Arduino. I have figured out how to receive values and decode the BCD, but I'm stuck on how to create the required values from a float (to transmit back).
The calculator sends a data packet, which has an exponent value, several data values, and a byte that contains information about negativity, imaginary parts, etc. Each data value is worth one hundredth of the previous one, so the first is the amount of 10s, the next the amount of 0.1s, the next the amount of 0.001s, etc. This continues on until the 0.0000000000001s, though this is out of the range of what I'll really need, so that level of accuracy is not really important to me. The output of my receiving program looks like this:
Exponent: 1
10s: 1
0.1s: 23
0.001s: 40
This represents 12.34.
The general equation I worked out was: (let a=10s, b=0.1s, e=exponent etc)
((a*10)+(b*0.1)+(c*0.001))*10^(E-1)
If the exponent were to change to two:
Exponent: 2
10s: 1
0.1s: 23
0.001s: 40
This would represent 123.4
This method of dropping by hundredths each time is presumably used because they can store two digits in each byte with BCD, so it is most efficient to let each row have two digits as each row is stored as one byte.
I have come up with an equation that can calculate the exponent by counting the amount of digits before the decimal point and subtracting two, however this seems messy as it involves strings. I think a purely mathematical solution would be more elegant, if it is possible.
What is the fastest and simplest way to go from a normal number (e.g. 123.4) into this arrangement?
A solution in Arduino language would be greatly appreciated, but any insight whatsoever into the mathematical process needed would be equally valued.
Edit regarding floats:
I should clarify - I will be dealing with floats in other parts of my program and would like my inputted values to be compatible with numbers of any size (within reason, as stated before). I have no problem with multiplying them to be ints or casting them as other datatypes.
Hah, that was fun!
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include <float.h>
struct num_s {
// exponent
int e;
// v[0] is *10
// v[1] is *0.01
// v[2] is *0.0001
// and so on...
// to increase precision increase array count
int v[6];
};
#define NUM_VALSCNT (sizeof(((struct num_s*)0)->v)/sizeof(((struct num_s*)0)->v[0]))
// creates num_s object from a double
struct num_s num_create(double v) {
struct num_s t;
// find exponent so that v <= 10
t.e = 0;
while (fabs(v) >= 10.0) {
++t.e;
v /= 10.0;
}
// for each output number get the integral part of number
// then multiply the rest by 100 and continue
for (size_t i = 0; i < sizeof(t.v) / sizeof(t.v[0]); ++i) {
const double tmp = fmod(v, 1.0);
t.v[i] = v - tmp;
v = tmp * 100;
}
return t;
}
// converts back from num object to double
double num_get(struct num_s t) {
double denom = 10;
double ret = 0;
for (size_t i = 0; i < sizeof(t.v) / sizeof(t.v[0]); ++i) {
ret += denom * t.v[i];
denom /= 100;
}
return ret * pow(10, t.e - 1);
}
void num_println(struct num_s t) {
printf("%f =", num_get(t));
for (size_t i = 0; i < sizeof(t.v) / sizeof(t.v[0]); ++i) {
printf(" %d", t.v[i]);
}
printf(" %d\n", t.e);
}
// returns the precision of numbers
// the smallest number we can represent in num object
double num_precision(void) {
return pow(0.1, (NUM_VALSCNT - 1) * 2) * 10;
}
int num_unittests(void) {
const double tests[][3] = {
{ 123.49, 123.5, 123.51, }
};
for (size_t i = 0; i < sizeof(tests) / sizeof(tests[0]); ++i) {
const double tmp = num_get(num_create(tests[i][1]));
if (!(tests[i][0] <= tmp && tmp <= tests[i][2])) {
return i + 1;
}
}
return 0;
}
int main() {
num_println(num_create(12.3456789));
num_println(num_create(123.5));
num_println(num_create(12.35));
printf("%d\n", num_unittests());
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm new to Arduino coding and I'm not sure what issue I'm having with displaying the variable as serialPrint. Here is part of my code:
void loop()
{
int force1raw = analogRead(FSR_PIN1);
int force2raw = analogRead(FSR_PIN2);
int force3raw = analogRead(FSR_PIN3);
float force1 = force1raw;
float force2 = force2raw;
float force3 = force3raw;
for (int i = 0; i < 1000; i++)
{
// Use ADC reading to calculate voltage:
float f1v = force1 * VCC / 1023.0;
// Use voltage and static resistor value to
// calculate FSR resistance:
float f1r = R_DIV * (VCC / f1v - 1.0);
}
Serial.println("Resistance 1: " + String(f1r) + " ohms");
// Estimate force based on slopes in figure 3 of
// FSR datasheet:
float force;
float f1g = 1.0 / f1r; // Calculate conductance
// Break parabolic curve down into two linear slopes:
if (f1g <= 600)
force1f = (f1g - 0.00075) / 0.00000032639;
else
force1f = f1g / 0.000000642857;
Serial.println("Force 1: " + String(force2f) + " g");
Serial.println();
delay(100);
Well,
Serial.println("Resistance 1: " + String(f1r) + " ohms");
it uses the variable f1r whose scope just ended.
In C++, when a variable is defined inside a scope (between some { and }), it does not exist outside of it.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
How can I integrate an equation including bessel functions numerically from "0" to "infinity" in Fortran or/and C?
I did in matlab, but it's not true for larger inputs and after a specific values , the bessel functions give completely wrong results(there is a restriction in Matlab)
There's a large number of analytic results for various integrals of the Bessel functions (see DLMF, Sect. 10.22), including definite integrals over precisely this range. You'd be much better off, and almost certainly faster and more accurate, trying hard to recast your expression into something that's integrable and using an exact result.
Last time I had to do with such things, it was state of the art to do simple integration of the intervals defined by the zero crossings. That is in most cases relatively stable and if the integrand is approaching zero reasonable fast easy to do.
As a starting point for playing around I´ve included a bit of code. Of course you need to work on the convergence detection and error checking. This is no production code but I thought maybe it provides a starting point for you. Its using gsl.
On my iMac this code takes about 2 µs per iteration. It will not become faster by including a hardcoded table for the intervals.
I hope this is of some use for you.
#include <iostream>
#include <vector>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_sf.h>
double f (double x, void * params) {
double y = 1.0 / (1.0 + x) * gsl_sf_bessel_J0 (x);
return y;
}
int main(int argc, const char * argv[]) {
double sum = 0;
double delta = 0.00001;
int max_steps = 1000;
gsl_integration_workspace * w = gsl_integration_workspace_alloc (max_steps);
gsl_function F;
F.function = &f;
F.params = 0;
double result, error;
double a,b;
for(int n=0; n < max_steps; n++)
{
if(n==0)
{
a = 0.0;
b = gsl_sf_bessel_zero_J0(1);
}
else
{
a = n;
b = gsl_sf_bessel_zero_J0(n+1);
}
gsl_integration_qag (&F, // function
besselj0_intervals[n], // from
besselj0_intervals[n+1], // to
0, // eps absolute
1e-4,// eps relative
max_steps,
GSL_INTEG_GAUSS15,
w,
&result,
&error);
sum += result;
std::cout << n << " " << result << " " << sum << "\n";
if(abs(result) < delta)
break;
}
return 0;
}
You can pretty much google and find lots of Bessel functions implemented in C already.
http://www.atnf.csiro.au/computing/software/gipsy/sub/bessel.c
http://jean-pierre.moreau.pagesperso-orange.fr/c_bessel.html
https://msdn.microsoft.com/en-us/library/h7zkk1bz.aspx
In the end, these use the built in types and will be limited to the ranges they can represent (just as MATLAB is). At best, expect 15 digits of precision using double precision floating point representation. So, for large numbers, they will appear to be rounded. eg. 1237846464123450000000000.00000
And, of course, others on Stack Overflow have looked into it.
C++ Bessel function for complex numbers