This solution would not accept any floats - c

Currently on one of the cs50x problem sets 'Cash', which is a simple 'ask for how much change is owed, then calculate how many coins are required' task, so not here asking for a solution but, I don't understand why this won't work.
While it does ask for an input, when I type in a float such as 5.96, it simply hangs. No returns, no errors whatsoever. I have to force it shut. The other thing is the while loop doing the same when set to 0, which is the intended way of doing things in order to get the exact number of coins.
I know how inefficient this code is and there are simpler ways of doing things. I just wish to understand the whys in order to avoid making the same mistakes moving on. Thanks.
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
// changes and other containers
int p = 1;
int n = 5;
int d = 10;
int q = 25;
int x = 0;
float c;
// get how much change is owed in float
do
{
c = get_float("Change owed: ");
}
while (c < 0);
// int conversion to avoid imprecision
int a = round(c * 100);
// 1 because 0 spits out an unknown error
while (a >= 1)
{
// if the converted amount is bigger than a quarter
if (a >= q)
{
// x = number of coins, a = amount left
x = a / q;
a = a % q;
}
else if (a >= d)
{
x = x + a / d;
a = a - a % d;
}
else if (a >= n)
{
x = x + a / n;
a = a - a % n;
}
else
{
x = x + a / p;
a = a - a % p;
}
}
printf("%i\n", x);
printf("%i\n", a);
}

Thanks to WhozCraig, I figured out that my logic was at fault.
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
// changes and other containers
int p = 1;
int n = 5;
int d = 10;
int q = 25;
int x = 0;
float c;
// get how much change is owed in float
do
{
c = get_float("Change owed: ");
}
while (c < 0);
// int conversion to avoid imprecision
int a = round(c * 100);
// 1 because 0 spits out an unknown error
while (a >= 1)
{
// if the converted amount is bigger than a quarter
if (a >= q)
{
// x = number of coins, a = amount left
x = a / q;
a = a % q;
}
else if (a >= d)
{
x = x + a / d;
a = a % d;
}
else if (a >= n)
{
x = x + a / n;
a = a % n;
}
else
{
x = x + a / p;
a = a % p;
}
}
printf("%i\n", x);
printf("%i\n", a);
}

Related

Optimization with a float in c

I am currently doing exercices on Kattis and I meet a problem with I think the float.
I must compare the size of matchstick with the size of box
Sibice problem on Kattis.com
Here is a picture of the exercise
I can make examples but when I submit I past only the first two...
Here is a picture of my submission
I don't have a trace or explication for know my errors... I tried to change the type of my variables but there is no change... I think the problems is float but I need it.
Here is my code
#include <stdio.h>
void sibice(float n, float w, float h)
{
float v = 0;
for(float i = 0; i != n; i += 1) {
scanf("%f", &v);
if(v < w + h / 2)
printf("DA\n");
if(v == w + h / 2)
printf("DA\n");
if(v > w + h / 2) {
printf("NE\n");
}
}
}
int main(void)
{
float n = 0;
float w = 0;
float h = 0;
scanf("%f %f %f", &n, &w, &h);
sibice(n, w, h);
return (0);
}
Do you think that I can optimize my code ?
Incorrect test
If a match can fit is a more like v*v <= h*h + w*w than v < w + h / 2. Can it diagonally fit?
See Pythagorean theorem
#include <math.h>
...
float hyp = hypotf(h,w); // sqrt(h*h + w*w)
for(float i = 0; i != n; i += 1) {
scanf("%f", &v);
// if(v < w + h / 2)
if(v < hyp)
No need for 3 tests
One test is sufficient.
if(v <= hyp) {
printf("DA\n");
} else {
printf("NE\n");
}
Integer math
As all calculations are whole numbers, code could use int only math.
void sibice(int n, int w, int h) {
int hyp2 = h*h + w*w;
for (int i = 0; i != n; i += 1) {
int v;
scanf("%d", &v);
if (v*v <= hyp2)
...
Other issues may exist
Why do you need to use float? With these changes the code passes the tests:
#include <stdio.h>
#include <stdlib.h>
void sibice(int n, int w, int h)
{
int v;
int result;
for (int i = 0; i != n; i += 1) {
result = scanf("%d", &v);
if (1 != result)
exit(1);
if (v * v <= w * w + h * h)
printf("DA\n");
else
printf("NE\n");
}
}
int main(void)
{
int n = 0;
int w = 0;
int h = 0;
int result = 0;
result = scanf("%d %d %d", &n, &w, &h);
if (3 != result)
return 1;
sibice(n, w, h);
return (0);
}

Feige Fiat Shamir Scheme not working

I'm trying to implement the Feige Fiat Shamir Identification Scheme in C (Arduino) and it works, but only when e = 0. When e = 1 it doesn't work.
How can I make it work?
#include <Wire.h>
int getGCD(int a, int b)
{
int c;
while (a != 0)
{
c = a;
a = b % a;
b = c;
}
return b;
}
int getCoprime(int n)
{
int coprime;
do
{
coprime = random(1, n);
}
while (getGCD(n, coprime) != 1);
return coprime;
}
//Preparation
int n = 7 * 3;
int s = getCoprime(n);
int v = (s * s) % n;
void loop ()
{
e = random(0, 2);
r = random(1, n);
int y = (r * (int)pow(s, e)) % n;
int x = (r * r) % n;
int ysqmodn = y * y % n;
int test = (x * (int)pow(v, e)) % n;
if(ysqmodn == test)
{
Serial.print("The current ICC matches. \n");
}
else
{
Serial.print(String(e));
Serial.print("\n");
}
delay(500);
}
It does work when e==1. When e==0 the computation is trivial, since s and v fall out due to power of 0 always being 1. This is the code copied and altered only enough to get it to compile.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
int random (int low, int high) {
return low + rand() % (high - low);
}
int getGCD(int a, int b) {
int c;
while (a != 0)
{
c = a;
a = b % a;
b = c;
}
return b;
}
int getCoprime(int n) {
int coprime;
do
{
coprime = random(1, n);
}
while (getGCD(n, coprime) != 1);
return coprime;
}
int main(void) {
int e, x, y, r, n, s, v, test, ysqmodn;
srand((unsigned)time(NULL));
n = 7 * 3;
s = getCoprime(n);
v = (s * s) % n;
e = random(0, 2);
r = random(1, n);
printf("n=%d, s=%d, e=%d, r=%d\n", n,s,e,r);
y = (r * (int)pow(s, e)) % n;
x = (r * r) % n;
ysqmodn = y * y % n;
test = (x * (int)pow(v, e)) % n;
if(ysqmodn == test)
printf("The current ICC matches. \n");
else
printf("%d\n", e);
return 0;
}
Sample results:
n=21, s=2, e=1, r=2
The current ICC matches.
n=21, s=11, e=0, r=12
The current ICC matches.
n=21, s=8, e=1, r=14
The current ICC matches.
n=21, s=17, e=1, r=13
The current ICC matches.
n=21, s=1, e=0, r=9
The current ICC matches.
n=21, s=4, e=0, r=13
The current ICC matches.

C function returns wrong value

float a, b;
float sa() { return a;};
int main() {
a = 10;
b = sa();
printf("%f", b);
return 0;
}
This is a simplified version of my code.
I believe the program should print 10 but it gives me really small numbers like -65550, not always the same but very alike.
I have used the debugger to check the value of variabe a right before it is returned and it is 10, so the function returns 10, but b is set to something like -65550. I don't understand why this happens.
I'd appreciate some intell.
Thanks in advance.
Here is the full code:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
int dimensiuni, nrBitiSolutie, bitiPeDimensiune, gasitInbunatatire, nrRulari;
float limInf, limSup, precizie, valoareFunctie, minim, minimNou, T;
char solutie[100000];
float solutieReala[100];
void generateRandomSolution();
void bitesToFloat();
void rastrigin();
void rosenbrock();
float nextFirstFit();
float nextBestFit();
void main() {
int k;
T = 10;
gasitInbunatatire = 1;
srand ( time(NULL) );
printf("Introduceti numarul de dimensiuni: ");
scanf("%d", &dimensiuni);
printf("Introduceti limita inferioara si cea superioara: ");
scanf("%f%f", &limInf, &limSup);
printf("Introduceti precizia: ");
scanf("%f", &precizie);
//calculam numarul de biti necesari ca sa reprezentam solutia
nrBitiSolutie = dimensiuni * ceil(log(limSup-limInf * pow(10, precizie)))/log(2.0);
bitiPeDimensiune = nrBitiSolutie/dimensiuni;
//generam o solutie random
generateRandomSolution();
bitesToFloat();
rastrigin();
minim = valoareFunctie;
printf("Pornim de la %f\n", minim);
while( (nrRulari < 10000) && (T > 0.001)) {
minimNou = sa(); //error occurs here. sa() returns about 200 but minimNou is set to -65550
if (minimNou < minim) {
printf("Minim nou: %f\n", minimNou);
minim = minimNou;
T *= 0.995;
}
nrRulari++;
}
printf("Minimul aproximat: %f\n", minim);
system("pause");
}
void generateRandomSolution() {
int l;
for (l = 0; l < nrBitiSolutie; l++) solutie[l] = rand()%2;
}
void bitesToFloat() {
int i, parcurse = 1, gasite = 0;
int variabila = 0;
float nr;
for (i = 0; i < nrBitiSolutie; i++) {
variabila = variabila<<1 | (int)solutie[i];
if(parcurse == bitiPeDimensiune) {
nr = (float)variabila / (float)pow(2, bitiPeDimensiune);
nr *= limSup-limInf;
nr += limInf;
nr *= pow(10, precizie);
nr = (int)nr;
nr /= pow(10, precizie);
parcurse = 0;
solutieReala[gasite++] = nr;
variabila = 0;
}
parcurse++;
}
}
void rastrigin() {
int i;
valoareFunctie = 10 * dimensiuni;
for (i = 0; i < dimensiuni; i++) {
valoareFunctie += pow((float)solutieReala[i], 2) - 10 * (float)cos(2 * 3.14 * (float)solutieReala[i]);
}
}
void rosenbrock() {
int i;
valoareFunctie = 0;
for (i = 0; i < dimensiuni - 1; i++) {
valoareFunctie += 100 * pow((solutieReala[i+1] - pow(solutieReala[i], 2)), 2) + pow((1-solutieReala[i]), 2);
}
}
float sa() {
int j;
for (j = 0; j < nrBitiSolutie; j++) {
solutie[j] = solutie[j] == 0 ? 1 : 0;
bitesToFloat();
rastrigin();
if (valoareFunctie < minim) return valoareFunctie;
else if ( (rand()/INT_MAX) < exp((minim - valoareFunctie)/T) )
return valoareFunctie;
else solutie[j] = solutie[j] == 0 ? 1 : 0;
}
return minim;
}
I have marked where the error occurs with error occurs here comment
You simplified the code incorrectly. In your simplification, you defined sa() before calling it. But in your full program, you call sa() before defining it. In the absence of a declaration, functions are assumed to return int. Since your function actually returns a float, the result is undefined. (In this case, you will read a garbage value from the top of the floating point stack and then the floating point stack will underflow, and things go downhill from there.)

Howto compute the factorial of x

how to get the value of an integer x, indicated by x!, it is the product of the numbers 1 to x.
Example: 5! 1x2x3x4x5 = 120.
int a , b = 1, c = 1, d = 1;
printf("geheel getal x = ");
scanf("%d", &a);
printf("%d! = ", a);
for(b = 1; b <= a; b++)
{
printf("%d x ", c);
c++;
d = d*a;
}
printf(" = %d", d);
how to get the som of an integer x, indicated by x!, is the product of the numbers 1 to x.
Did you mean factorial of x ?
Change d = d*a; to d = d*b inside the loop
You can simply do:
for(b = 1; b <= a; b++) {
d *= b;
}
// d now has a!
This is the optimal implementation in size and speed:
int factorial(int x)
{
static const int f[13] = { 1, 1, 2, 6, 24, 120, /* ... */ };
if ((unsigned)x < (sizeof f/sizeof f[0])) return f[x];
else return INT_MAX+1; /* or your favorite undefined behavior */
}
Hint: x! (x factorial) does not fit in an int except for very very small values of x.
Try
d = d * b;
instead of
d = d * a
and it should work fine
You actually have a lot of redundant code there, that might be why you did not spot the error yourself.
To calculate the factorial, you only need the accumulator (d in the above code) and the input (a). Why?
My code is not good as other but it works for me:
#include <iostream>
using namespace std;
unsigned int fattoriale (int n){
if (n == 1){
return 1;
}
else {
return n * fattoriale(n-1);
}
}
int main() {
int tmp, num;
cin >> num;
tmp = fattoriale(num);
cout << "Stampo il fattoriale del numero inserito: " << tmp << endl;
}
int factorial(int x)
{
int f;
if (x == 0)
{
f = 1;
}
else if (x > 0)
{
f = x*factorial(x-1);
}
return f;
}
int main()
{
int n = 0;
cout << factorial(n);
return 0;
}

Perceptron learning algorithm not converging to 0

Here is my perceptron implementation in ANSI C:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float randomFloat()
{
srand(time(NULL));
float r = (float)rand() / (float)RAND_MAX;
return r;
}
int calculateOutput(float weights[], float x, float y)
{
float sum = x * weights[0] + y * weights[1];
return (sum >= 0) ? 1 : -1;
}
int main(int argc, char *argv[])
{
// X, Y coordinates of the training set.
float x[208], y[208];
// Training set outputs.
int outputs[208];
int i = 0; // iterator
FILE *fp;
if ((fp = fopen("test1.txt", "r")) == NULL)
{
printf("Cannot open file.\n");
}
else
{
while (fscanf(fp, "%f %f %d", &x[i], &y[i], &outputs[i]) != EOF)
{
if (outputs[i] == 0)
{
outputs[i] = -1;
}
printf("%f %f %d\n", x[i], y[i], outputs[i]);
i++;
}
}
system("PAUSE");
int patternCount = sizeof(x) / sizeof(int);
float weights[2];
weights[0] = randomFloat();
weights[1] = randomFloat();
float learningRate = 0.1;
int iteration = 0;
float globalError;
do {
globalError = 0;
int p = 0; // iterator
for (p = 0; p < patternCount; p++)
{
// Calculate output.
int output = calculateOutput(weights, x[p], y[p]);
// Calculate error.
float localError = outputs[p] - output;
if (localError != 0)
{
// Update weights.
for (i = 0; i < 2; i++)
{
float add = learningRate * localError;
if (i == 0)
{
add *= x[p];
}
else if (i == 1)
{
add *= y[p];
}
weights[i] += add;
}
}
// Convert error to absolute value.
globalError += fabs(localError);
printf("Iteration %d Error %.2f %.2f\n", iteration, globalError, localError);
iteration++;
}
system("PAUSE");
} while (globalError != 0);
system("PAUSE");
return 0;
}
The training set I'm using: Data Set
I have removed all irrelevant code. Basically what it does now it reads test1.txt file and loads values from it to three arrays: x, y, outputs.
Then there is a perceptron learning algorithm which, for some reason, is not converging to 0 (globalError should converge to 0) and therefore I get an infinite do while loop.
When I use a smaller training set (like 5 points), it works pretty well. Any ideas where could be the problem?
I wrote this algorithm very similar to this C# Perceptron algorithm:
EDIT:
Here is an example with a smaller training set:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float randomFloat()
{
float r = (float)rand() / (float)RAND_MAX;
return r;
}
int calculateOutput(float weights[], float x, float y)
{
float sum = x * weights[0] + y * weights[1];
return (sum >= 0) ? 1 : -1;
}
int main(int argc, char *argv[])
{
srand(time(NULL));
// X coordinates of the training set.
float x[] = { -3.2, 1.1, 2.7, -1 };
// Y coordinates of the training set.
float y[] = { 1.5, 3.3, 5.12, 2.1 };
// The training set outputs.
int outputs[] = { 1, -1, -1, 1 };
int i = 0; // iterator
FILE *fp;
system("PAUSE");
int patternCount = sizeof(x) / sizeof(int);
float weights[2];
weights[0] = randomFloat();
weights[1] = randomFloat();
float learningRate = 0.1;
int iteration = 0;
float globalError;
do {
globalError = 0;
int p = 0; // iterator
for (p = 0; p < patternCount; p++)
{
// Calculate output.
int output = calculateOutput(weights, x[p], y[p]);
// Calculate error.
float localError = outputs[p] - output;
if (localError != 0)
{
// Update weights.
for (i = 0; i < 2; i++)
{
float add = learningRate * localError;
if (i == 0)
{
add *= x[p];
}
else if (i == 1)
{
add *= y[p];
}
weights[i] += add;
}
}
// Convert error to absolute value.
globalError += fabs(localError);
printf("Iteration %d Error %.2f\n", iteration, globalError);
}
iteration++;
} while (globalError != 0);
// Display network generalisation.
printf("X Y Output\n");
float j, k;
for (j = -1; j <= 1; j += .5)
{
for (j = -1; j <= 1; j += .5)
{
// Calculate output.
int output = calculateOutput(weights, j, k);
printf("%.2f %.2f %s\n", j, k, (output == 1) ? "Blue" : "Red");
}
}
// Display modified weights.
printf("Modified weights: %.2f %.2f\n", weights[0], weights[1]);
system("PAUSE");
return 0;
}
In your current code, the perceptron successfully learns the direction of the decision boundary BUT is unable to translate it.
y y
^ ^
| - + \\ + | - \\ + +
| - +\\ + + | - \\ + + +
| - - \\ + | - - \\ +
| - - + \\ + | - - \\ + +
---------------------> x --------------------> x
stuck like this need to get like this
(as someone pointed out, here is a more accurate version)
The problem lies in the fact that your perceptron has no bias term, i.e. a third weight component connected to an input of value 1.
w0 -----
x ---->| |
| f |----> output (+1/-1)
y ---->| |
w1 -----
^ w2
1(bias) ---|
The following is how I corrected the problem:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define LEARNING_RATE 0.1
#define MAX_ITERATION 100
float randomFloat()
{
return (float)rand() / (float)RAND_MAX;
}
int calculateOutput(float weights[], float x, float y)
{
float sum = x * weights[0] + y * weights[1] + weights[2];
return (sum >= 0) ? 1 : -1;
}
int main(int argc, char *argv[])
{
srand(time(NULL));
float x[208], y[208], weights[3], localError, globalError;
int outputs[208], patternCount, i, p, iteration, output;
FILE *fp;
if ((fp = fopen("test1.txt", "r")) == NULL) {
printf("Cannot open file.\n");
exit(1);
}
i = 0;
while (fscanf(fp, "%f %f %d", &x[i], &y[i], &outputs[i]) != EOF) {
if (outputs[i] == 0) {
outputs[i] = -1;
}
i++;
}
patternCount = i;
weights[0] = randomFloat();
weights[1] = randomFloat();
weights[2] = randomFloat();
iteration = 0;
do {
iteration++;
globalError = 0;
for (p = 0; p < patternCount; p++) {
output = calculateOutput(weights, x[p], y[p]);
localError = outputs[p] - output;
weights[0] += LEARNING_RATE * localError * x[p];
weights[1] += LEARNING_RATE * localError * y[p];
weights[2] += LEARNING_RATE * localError;
globalError += (localError*localError);
}
/* Root Mean Squared Error */
printf("Iteration %d : RMSE = %.4f\n",
iteration, sqrt(globalError/patternCount));
} while (globalError > 0 && iteration <= MAX_ITERATION);
printf("\nDecision boundary (line) equation: %.2f*x + %.2f*y + %.2f = 0\n",
weights[0], weights[1], weights[2]);
return 0;
}
... with the following output:
Iteration 1 : RMSE = 0.7206
Iteration 2 : RMSE = 0.5189
Iteration 3 : RMSE = 0.4804
Iteration 4 : RMSE = 0.4804
Iteration 5 : RMSE = 0.3101
Iteration 6 : RMSE = 0.4160
Iteration 7 : RMSE = 0.4599
Iteration 8 : RMSE = 0.3922
Iteration 9 : RMSE = 0.0000
Decision boundary (line) equation: -2.37*x + -2.51*y + -7.55 = 0
And here's a short animation of the code above using MATLAB, showing the decision boundary at each iteration:
It might help if you put the seeding of the random generator at the start of your main instead of reseeding on every call to randomFloat, i.e.
float randomFloat()
{
float r = (float)rand() / (float)RAND_MAX;
return r;
}
// ...
int main(int argc, char *argv[])
{
srand(time(NULL));
// X, Y coordinates of the training set.
float x[208], y[208];
Some small errors I spotted in your source code:
int patternCount = sizeof(x) / sizeof(int);
Better change this to
int patternCount = i;
so you doesn't have to rely on your x array to have the right size.
You increase iterations inside the p loop, whereas the original C# code does this outside the p loop. Better move the printf and the iteration++ outside the p loop before the PAUSE statement - also I'd remove the PAUSE statement or change it to
if ((iteration % 25) == 0) system("PAUSE");
Even doing all those changes, your program still doesn't terminate using your data set, but the output is more consistent, giving an error oscillating somewhere between 56 and 60.
The last thing you could try is to test the original C# program on this dataset, if it also doesn't terminate, there's something wrong with the algorithm (because your dataset looks correct, see my visualization comment).
globalError will not become zero, it will converge to zero as you said, i.e. it will become very small.
Change your loop like such:
int maxIterations = 1000000; //stop after one million iterations regardless
float maxError = 0.001; //one in thousand points in wrong class
do {
//loop stuff here
//convert to fractional error
globalError = globalError/((float)patternCount);
} while ((globalError > maxError) && (i<maxIterations));
Give maxIterations and maxError values applicable to your problem.

Resources