Monthly Archives: January 2021

程序代写代做代考 scheme algorithm CSE 2421 Lab 2

CSE 2421 Lab 2
Learning C, redirection,
bit shifting, and bitwise operations
Due: Thursday 4 Feb 2021 11:59 PM
Early: 2 bonus points if submitted by Tuesday 2 Feb 2021 11:59 PM
Late: Friday 5 Feb 2021 11:59 PM
We¡¯ll be using Carmen¡¯s timestamps to determine lateness or not. If you are not enrolled, you may send me an email with the zip file. If you are unable to submit by the deadline, you need to send me a screenshot of your finished files with the clock visible and then *still* submit to Carmen when you can.
This lab contains three parts. Make sure you do all of them!
Something you should do before getting started on the lab is creating your readme file. Simply create a file called ¡°readme¡± and include your name at the top. As you progress through the lab, you may see different parts (labeled things like Part 1). When you see this, write it down in your readme. While in a numbered part of a lab, you¡¯ll come across various questions, prepended with a bolded Q and a number (such as Q5). When you see this, include the Q and the number, along with you answer to the question(s) in the file. A brief example:
Name: Rob LaTour
I certify that I completed all of the work myself with no aid from anyone aside from the instructor or the undergraduate graders.
Part 1:
Q1: Don¡¯t make fun of me, but my favorite color is gray
Q2: The definitive answer is that Han did shoot first. The original version is the one that captured the heart of the public, and thus the director lost creative control. In this essay I will…

Part 1: Encryption
For this lab, we will be implementing a relatively simple (and limited) encryption/decryption scheme. The first part of the lab requires you to produce a c program that encrypts a plaintext file into another file. I highly recommend breaking this task up into three chunks: first produce an executable that can, through redirection, read an input file character by character and print those characters to an output file. Next, produce an executable that reads in 8 characters from the input file, character by character, then writes those to the output file. Your executable should handle the case where there are fewer than 8 characters in the input file and still work to transfer those characters to the output file. Finally, work on tackling the encryption scheme pictured below.
NOTE: Your code should be written to be as modular as possible. Although the scheme described here reads data in and processes it in chunks of 8 bytes, your program should be (relatively easily) extensible to a scheme that uses larger batches. With this in mind, I recommend creating a header file to define macros rather than using the constant 8 everywhere. You may find it useful to put other things in this header as well!
Our simple encryption scheme is pictured here:
In Figure 1, we have 8 characters (labeled I sub 1 through 8). Each of the lowercase letters in the boxes represents a bit (a 1 or a 0). At a high level, we are simply taking the bits that make up our 8th character and replacing the most significant bit in each of our other characters with that bit.
Your task is to create an executable file that will read in 8 characters at a time from an input file, encrypt those following this scheme, and then write the encrypted 7 characters to an output file. That process should be repeated until the end of the file is reached. If the number of characters in the file isn¡¯t a multiple of 8 (and it likely won¡¯t be), your program should simply

transcribe the characters without changing them. This task will heavily make use of bit shifting and bitwise operations!
Create a set of test files to make sure your program is producing reasonable output. You can choose exactly what you want your test files to look like, but you¡¯ll need to justify why you created them shortly. There are 2 files I will require you to create, however: One is an input file with exactly 8 characters in it. One is the corresponding ¡°expected output¡± file. Do the encryption scheme by hand and write out this file. When you test your encryption scheme with the 8-character-long input file, you can then use the Linux command diff to ensure that the files are identical. When you¡¯re confident that your program is working, run each of your test files through your program and keep them around. They¡¯ll be useful in Part 2!
Q1: Briefly justify why you created the test files you¡¯re including with your lab. To help you write this answer, consider the following: what potential failure point does this test file cover? What kind of test case does this file represent, a routine, boundary, or challenging case?
Q2: Copy down the 8 characters in your required test file as well as the 7 characters in your ¡°expected output¡± file. Why did you choose the characters that you did?
Q3: Describe one way that this encryption scheme could be modified (from an algorithmic perspective) quickly and easily in the event that this particular strategy was foiled. Note that there are a lot of possible correct answers to this question!
Q4: As a follow-up to the question above, describe at a high level how we could generalize our code such that an extra input or macro could swap between schemes.
Part 2: Decryption
For the second part of this lab, you¡¯re going to create an executable that can decrypt your encrypted text back to plaintext. The procedure will essentially be the inverse of what was done above. The program should read in an input file 7 characters at a time, decrypt those, then repeat until the file ends. Once again, if there are fewer than 7 characters, your program should simply transcribe the characters as written.
If your program is able to read in a full 7 characters, then the most significant bit of each makes up the bits of the 8th character of plaintext. Consult the diagram above if you are confused! Once again, we will have to do a lot of bit shifting and bitwise operations.
You can use the output of Part 1 to test your implementation of Part 2!
Q1: You may have noticed something unexpected/bad can happen with this scheme as described. Namely, it is possible to correctly follow the encryption scheme, then immediately correctly follow the decryption scheme, and then end up with garbage as a result. How could this happen? Why?

Q2: Describe one way that the problem in Q1 could be fixed. Once again, there are many correct answers here!
Part 3: Making the graders¡¯ eyes bleed
This part is largely for fun, but it will also include some miscellaneous questions about the lab as a whole, since it assumes you have finished both Part 1 and Part 2.
Your task is to create an alternative implementation to your code in either Part 1 or Part 2. MAKE SURE THAT YOU CREATE A COPY OF THE FILE BEFORE YOU START EDITING. IT WOULD BE A TRAVESTY FOR YOU TO RUIN SOMETHING YOU ALREADY WORKED ON FOR SO LONG. Your code should be as unreadable as possible while still maintaining the full functionality. For full credit, your code should include at least one goto, break, and continue. Additionally, there should be at least one loop or if construct without a block under it, and at least one conditional that uses an implicit comparison rather than an explicit one. While not an expectation, feel free to rename variables to be have similar and nondescriptive names, delete comments, and put multiple statements on the same line. Please remember, however, that the code must still function identically to whichever of your functions you rewrote. The graders will test for this.
Q1: Did you choose to mangle a copy of your encryption code or your decryption code? Why?
Q2: Answer this question honestly: at the time of writing this question, is it easy for you to read and understand what your mangled code does? Do you think it would be several months from now?
Q3: In this portion of the lab, you took what was (ostensibly) good code and made it hard to read. Do you think that it would be easier or harder to take hard to read code and make it good? Why?
And now for some questions about the lab as a whole:
Q4: Some of you may have noticed that there is an unwritten assumption about the input data that makes a dramatic impact on the functionality of this encryption/decryption scheme. What¡¯s the unwritten assumption?
Q5: If this assumption is not true, what part of the process could fail?

程序代写代做代考 SOST70011 Introduction to Statistical Modelling, 2020

SOST70011 Introduction to Statistical Modelling, 2020
Assessment (100% of course grade): 
Lack of physical activity and depression
Major clinical depression can be a severely debilitating illness, but even mild depressive episodes can severely affect quality of life. Roshanaei-Moghaddam et al. (2009) reviewed the relationship between physical activity and depression. There is certainly a negative correlation between physical activity and depression, such that lower levels of activity are associated with higher levels of depression, but it is unclear as to what proportion of the relationship is causal, as opposed to spurious. For example, there may be confounding factors, such as attributes of individuals that make them both more likely to engage in physical activity and less likely to suffer depression.
In an effort to disentangle spurious from causal effects, you have decided to analyse data from the English Longitudinal study of Ageing (ELSA). This study surveyed a sample of English householders aged 50 or more, across multiple occasions, two years apart. The first occasion, or wave, was in 2002 and the second wave was in 2004. Figure 1 shows the hypothesised relationships between depression (cesd) and lack of activity (notact) across the two waves, plus some key additional variables. The central causal relationships of interest are shown with dashed arrows.
male1
age1
cesd1
notact1
illness1
cesd2
notact2
Figure 1: Directed Acyclic Graph of the hypothesised causal relationships between lack of physical activity (notact1 & notact2) and depression (cesd1 & cesd2) across two waves of ELSA.
male1
age1
cesd1
notact1
illness1
cesd2
notact2
Figure 1: Directed Acyclic Graph of the hypothesised causal relationships between lack of physical activity (notact1 & notact2) and depression (cesd1 & cesd2) across two waves of ELSA.
Data
The variables shown in Figure 1 were measured in ELSA. These variables are described in Tables 1 and 2, below. Table 1 describes the data in the “wide” format file “elsa12wide.csv”. Table 2 describes the data in the “long” format file “elsa12long.csv”.

Table 1: Variables from the DAG in Figure 1, as measured in the English Longitudinal Study of Ageing (ELSA), in the “wide” format file “elsa12wide.csv”.
Variable
Description
Coding
0. id
Respondent identifier
arbitrary numerical label
1. age1
Chronological age in wave 1 (2002)
Years since birth (in 2002)
2. male1
Biological sex in wave 1
Male = 1, female = 0
3. illness1
Limiting longstanding illness, self-declared in wave 1
Has illness = 1, no illness = 0
4. cesd1
Centre for Epidemiological Studies’ Depression (cesd) scale score, wave 1
Score from 0 to 8 (higher score = more depressed)
5. cesd2
as above, in wave 2 (2004)
as above
6. notact1
Self-declared lack of moderate physical activity at least once a week, in wave 1
1 = no moderate physical activity at least once a week, 
0 = at least some moderate physical activity
7. notact2
as above, in wave 2
as above

Table 2: Variables from the DAG in Figure 1, as measured in the English Longitudinal Study of Ageing (ELSA), in the “long” format file “elsa12long.csv”.
Variable
Description
Coding
0. id
Respondent identifier
arbitrary numerical label
1. age1
Chronological age in wave 1 (2002)
Years since birth, in 2002.
2. male1
Biological sex in wave 1
Male = 1, female = 0
3. illness1
Limiting longstanding illness, self-declared in wave 1
Has illness = 1, no illness = 0
4. cesd
Centre for Epidemiological Studies’ Depression (cesd) scale score, for waves 1 and 2
Score from 0 to 8 (higher score = more depressed)
5. notact
Self-declared lack of moderate physical activity at least once a week, for waves 1 and 2
1 = no moderate physical activity at least once a week, 
0 = at least some moderate physical activity
6. wave
ELSA wave identifier
1 = wave 1 (2002), 2 = wave 2 (2004)

Questions to answer
Use the R package and the data contained in the two files to carry out the tasks and answer the questions below:
• Fit a single-level model using the wide format data for the unconditional effect of notact1 -> cesd2 (i.e. a model with cesd2 as the outcome and notact1 as the sole predictor, and no additional “third” variables).
• Discuss the statistical and substantive meaning of the estimated model results (e.g. b parameters & SEs, p-values, R-square). [8 marks]
• Discuss the assumptions of this model (causal and statistical), and how they affect what you can conclude about the relationship between physical activity and depression in the study population. [4 marks]
• Based upon the DAG in Figure 1, specify and fit a single-level model using the wide format data to evaluate the total causal effect of notact1 -> cesd2.
• Explain the reasoning behind your choice of model specification, i.e. which variables did you choose to include as additional predictors in the model, if any. [8 marks]
• Discuss the changes in the estimated model results (e.g. b parameters, SEs, p-values, R-square), and their statistical and substantive meanings. [12 marks]
• Discuss the assumptions of this model (causal and statistical), and how they affect what you can conclude about the relationship between physical activity and depression in the study population. [8 marks]
• Fit a single-level model using the wide format data for the unconditional effect of cesd1 -> notact2 (i.e. a model with notact2 as the outcome and cesd1 as the sole predictor, and no additional “third” variables).
• Discuss the statistical and substantive meaning of the estimated model results (e.g. b parameters, SEs, p-values, R-square). [10 marks]
• Discuss the assumptions of this model (causal and statistical), and how they affect what you can conclude about the relationship between depression and physical activity in the study population. [5 marks]
• Based upon the DAG in Figure 1, specify and fit a single-level model using the wide format data to evaluate the total causal effect of cesd1 -> notact2.
• Explain the reasoning behind your choice of model specification, i.e. which variables did you choose to include as additional predictors in the model, if any. [10 marks]
• Discuss the changes in the estimated model results (e.g. b parameters, SEs, p-values, R-square), and their statistical and substantive meaning. [15 marks]
• Discuss the assumptions of this model (causal and statistical), and how they affect what you can conclude about the relationship between physical activity and depression in the study population. [10 marks]
• Consider together the models from questions 2. and 4. Did you use the same predictor variables in each model or different ones, and why? When viewed together, what do the results from these models tell us about the relationship between physical activity and depression in the study population? [10 marks]
• Fit a model using the long format data to evaluate the proportion of variance in depression scores (cesd) between- and within-individuals.
• What is the proportion of variance in depression scores (cesd) attributable to variation between individuals in average depression levels over the two years? 
[5 marks]
• What is the proportion of variance in depression scores (cesd) attributable to changes within-individuals over the two years? [5 marks]
• Fit a model using the long format data to evaluate the proportion of variance in depression scores (cesd) across the two years that is attributable to differences in the age of participants in the first wave (age1).
• Comment on the size of the variation attributable to age differences, the substantive meaning of the differences, and whether these sample differences can be generalized to the population. [20 marks]
• Fit a model using the long format data to evaluate the proportion of variance in depression scores (cesd) across the two years that is attributable to differences in the sex of participants in the first wave (male1).
• Comment on the size of the variation attributable to sex differences, the substantive meaning of the differences, and whether these sample differences can be generalized to the population. [20 marks]
Copy/paste the R script that you used to run the models for the questions above into an appendix of your submission. [You will not be graded on the correctness of this appendix. Marks will neither be awarded nor penalized for your R code. Rather it will be used to help in the understanding your models and results. Failure to include an R appendix will results in a penalty of 5 marks.]
Guidance notes
• Your submission should answer each of the 8 questions above. There are 150 marks available in total across the 8 questions.
• You should use the models we discussed in class to answer the questions. Different questions will require different models, so be sure to mention briefly which model you chose and why.
• Good answers are those that clearly address all parts of the question.
• Use descriptive statistics and/or derived quantities (such as model-predicted values) to support and justify your answers, where this will help you to answer the question clearly.
• You may re-code, centre, and / or derive new variables if it will help you answer the questions. Be sure to clearly describe and justify any such manipulation of the data.
• If your answer requires that you compute additional information not contained in the model output, be sure to show your working out.
• Your answers to questions 2.b. and 4.b. will be marked without regard to whether you answered questions 2.a. and 4.a. correctly, i.e. even if you got questions 2.a. or 4.a. wrong, it is still possible to get full marks for questions 2.b., 4.b.
• Supporting and justifying your answers with references to books and articles in the course reading lists, and other scholarly material, is encouraged and will help contribute to a higher mark. Provide a full reference for any work that you do cite. Include no more than 7 citations in your answer.
• The word limit for your submission is 3,000 words. Note that this is a limit, not a target; you are permitted to use fewer than 3,000 words, but not more.
• The word limit includes all of the words in the main text of your answer, including headings, but does not include references or the R appendix. (You do not need to repeat the full text of the questions above in your answer. Simply putting e.g. Q1.a., Q1.b., will be fine.)
• Submit your report via the Turnitin portal on Blackboard – it’s in the “Assessment” section. Deadline for submission is 2 PM, Friday 29th of January 2021.

Reference
Roshanaei-Moghaddam, B., Katon, W.J., Russo, J. (2009). The longitudinal effects of depression on physical activity. General Hospital Psychiatry. Volume 31, Issue 4, pages 306-315. https://doi.org/10.1016/j.genhosppsych.2009.04.002.

程序代写代做代考 matlab algorithm Department of Engineering/Informatics, King’s College London Nature-Inspired Learning Algorithms (7CCSMBIM)

Department of Engineering/Informatics, King’s College London Nature-Inspired Learning Algorithms (7CCSMBIM)
Assignment 1
This coursework is assessed. A type-written report needs to be submitted online through KEATS by the deadline specified on the module’s KEATS webpage.
Q1 Binary Genetic Algorithm by Hand
a) Write down the first 7 digits of your student ID as s1s2s3s4s5s6s7. Form an 8-digit number as s2s3s4s5s6s7b1b2 where the two digits b1b2 denote your day of birth. (5 Marks)
b) Write down the cost function with two variables: f(x,y) = −(s2 +s3)x2 +
(s4 + s5)xy − (s6 + s7)y2 − (b1 + b2). In the following, we are going to find the
optimal solution for the optimisation problem: min f (x, y) using binary genetic x,y
algorithm.
(5 Marks)
c) Population Initialisation: Create a population with 8 chromosomes and list them in a table with the headings of ‘n’, ‘Chromosome’, ‘Decoded x, y’ and ‘Cost’ where n denotes the chromosome number. It is assumed that both variables x and y are in the range of −(s1 +s2) and s+s6 +s7 where s de- notes the largest digit among {s1, s2, s3, s4, s5, s6, s7}. The 8 chromosomes are [s2, s3], [s4, s5], [s6, s7], [b1, b2], [s3, s2], [s5, s4], [s7, s6], [b2, b1] where the first and the second digits represent x and y, respectively. 5-bit binary representation is employed for each digit resulting in 10-bit binary number for each chromosome.
(10 Marks)
d) Natural Selection: Show the ranked population after the process of Natural Selection with Nkeep = 4 in a table with the heading of ‘n’, ‘Chromosome’, ‘Decoded x, y’ and ‘Cost’. (10 Marks)
e) Selection: Using the cost weighting technique, show the probability table with the heading of ‘n’, ‘Chromosome’, ‘Decoded x, y’, ‘Cost’, ‘Cn = cn − cNkeep+1 ’,
n
‘Pn’ and ‘􏰀 Pn’. (10 Marks)
i=1
f) Crossover: Show the population after the process of Single-Point Crossover.
The chromosomes are selected for crossover according to the probability table
in the Selection process. The first pair of parents are chosen according to the
random numbers { s2 , 1 − s2 }. The next pair of parents s2 +s3 +s4 +s5 +s6 s2 +s3 +s4 +s5 +s6
are the rest two chromosomes in the pool of Nkeep. If the remaining number
of chromosomes is more than two. Make a remark and randomly pick two as
the second pair of parents. The crossover point for the first pair of parents is
right after the round(s2+s3 )th bit and the crossover point for the second pair 2
of parents is right after the round(s4+s5 )th bit, where the operator round(·) 2
1

rounds off the value to the nearest integer. Different colours should be used to show clearly where each part of the chromosome goes to in the crossover process. Note: The left most bit of the chromosome is the first bit. (10 Marks)
g) Mutation: Show the population in a table with the heading of ‘n’, ‘Chromo- some’, ‘Chromosome after mutation’, ‘Decoded x, y’ and ‘Cost’. The mutation rate is μ = 0.25. Calculate the number of bits to be mutated (#mutation) and randomly choose #mutation bits of your choice. Highlight the mutated bits.
(10 Marks) Q2 Denote R1 as the remainder of s2+s3+s4 . Write a Matlab script to find the minimum
9
of the function R1 + 1 in Appendix using binary genetic algorithm. All variables are
in the range of −20 and 20. The precision of the solution should be up to 4 decimal places.
a) Show your calculation getting R1. (5 Marks)
b) Determine the number of bits for each variable for binary decoding. Explain
your answer. (5 Marks)
c) Run the procedure of binary genetic algorithm for 10 times with the combi- nations of population size (p or Npop): 10, 50 100 and μ : 0.1, 0.5, 0.9. 9 combinations in total. Obtain the best the worst costs of the 10 runs for each combination; the mean and the standard deviation of the best the worst costs for the 10 runs for each combination. Specify other control parameters of binary genetic algorithm used in this question, e.g., number of iterations, population size, Nkeep, methods of crossover and mutation, etc. List the results in Table 1 and Table 2. (20 Marks)
d) Comment briefly on the results obtained (with support/evidence) in terms of reliability and sensitivity of the binary genetic algorithm. (10 Marks)
2

“Runs” Number
p = 10 μ = 0.1
p = 10 μ = 0.5
p = 10 μ = 0.9
p = 50 μ = 0.1
p = 50 μ = 0.5
p = 50 μ = 0.9
p = 100 μ = 0.1
p = 100 μ = 0.5
p = 100 μ = 0.9
1
2
3
4
5
6
7
8
9
10
Mean
Standard Deviation
Best Cost
Worst Cost
Table 1: Statistics of 10 runs.
Mean of “Mean”
Standard deviation of “mean”
Mean of “Standard Deviation”
Standard deviation of “Standard Deviation”
Mean of “Best Cost”
Standard deviation of “Best Cost”
Mean of “Worst Cost”
Standard deviation of “Worst Cost”
N = 2 + s2 + s3 N
F1: 􏰀 􏰁|xi| + cos(xi)􏰂 i=1
N
F2: 􏰀 􏰁|xi| + sin(xi)􏰂
i=1 N
F3: 􏰀x2i i=1
N−1
F4: 􏰀 􏰃100(xi+1 − x2i )2 + (1 + xi)2􏰄
i=1
Table 2: Overall Statistic.
Appendix 1: Test Functions
3

N
F5: 10N + 􏰀(x2i − 10 cos(2πxi))
i=1
􏰀N x2i 􏰅N
F6: 1 + 4000 − cos(xi) i=1 i=1
sin2 􏰃􏰆x2 + x2􏰄 − 0.5 12
F7: 0.5 +
F8: (x21 + x2)0.25 sin 􏰁30((x1 + 0.5)2 + x2)0.1􏰂 + |x1| + |x2|
F9: −x1 sin􏰃􏰆|x1 −(x2 +9)|􏰄−(x2 +9)sin􏰃􏰆|0.5×1 +x2 +9|􏰄
In the above test functions, all xi, i = 1, 2, · · · , N, are decision variables.
Marking: The learning outcomes of this assignment are that students will understand the fundamental principle of binary genetic algorithm (BGA) and appreciate the BGA performance through the evaluation of some benchmark functions. The assessment will look into the knowledge and understanding on the topics. When answering the questions, show/explain/describe clearly the steps with reference to the equations/theory/algorithms (stated in the lecture slides). When making comments, provide statements with support from the results obtained.
Purposes of Assignment: This assignment is designed to reinforce the understand- ing of Genetic Algorithm by going through every single step and to get an idea how it performs when applying the Genetic Algorithm to solve a numerical problem. After do- ing this assignment, students should be aware of the capability and limitations of Genetic Algorithm and thus know what to note when applying it.
1 + 0.1(x21 + x2)
4

程序代写代做代考 matlab 1 Lab 1b: Iteration and error (due Sun Jan 31, 11:59 PM)

1 Lab 1b: Iteration and error (due Sun Jan 31, 11:59 PM)
In this lab you will investigate the effect of rounding errors in computing some simple expressions. Take a close look at the submission requirements at the end of the lab script to ensure you know what is expected to be handed in. A helpful tip: If you keep a word-processor file open and paste in results, plots, and explanations as you go along it will save you a lot of time getting the report together. You will also investigate the effect of rounding errors in computing some simple expressions.
Working and submitting in Teams of 2: We will help find you a partner.
1.1 Taylor series and error
Recall that the truncated Taylor series of a function f(x) about a point x0 is given by:
Tn(x) = 􏰀n f(k)(x0)(x − x0)k (1)
For f (x) = log x the task of evaluating (1) about x0 = 1 yields
Tn(x) =
k (x − 1)k (2)
k! k=0
􏰀n (−1)k−1
Problem 1
k=1
(a) Derive a Taylor series with n + 1 terms and the associated truncation error for the function f(x)= log(x)−x+1. (3)
(x−1)2
Your expression for the Taylor series should be general, similar to the series for log(x) (see Lab1A for examples of such computations). Note that this is actually much easier if you start with the Taylor series for log x and write out the first few terms explicitly starting with log(x) = (x − 1) + . . ., rather than starting from the definition above.
(b) Construct an expression that bounds the truncation error, assuming n > 2, for a given value of x. See especially the review material and examples related to Taylor’s series with remainder in Section 0.5 of the Text by Sauer.
Problem 2
(a) Modify an M-file for Taylor Series from Lab1A (e.g. for exp(x) without using Horner) to compute and plot the Taylor series and f(x) from problem 1 above (an M-file is expected to be handed in for this part with filename lab1bP2.m).
A couple of implementation hints that may be useful:
(i) Note that the loop does not have to start with 1.
(ii) Note that the first term in the series is now −1/2 rather than 0 so you will need to
1

change the initialization. A useful function to do this is the Matlab ones function which you can multiply by −0.5 to get the appropriate initialization.
(iii) When calculating f(x) with a vector argument x instead of a scalar, you need to use the vector operators for division ./ and powers .ˆ (i.e. with the . modifying the normal operator).
(b) Plot a graph of f(x) and its Taylor series with 4 terms (up to the cubic term) using 50 points over the range (0.999, 1.001). If you have done this correctly, the curves should be essentially indistinguishable.
Problem 3
(a) Change the range of your plot in problem 2b above to (1−10−7,1+10−7). The two curves should now look very different.
(b) Change the script so that it plots the absolute and relative errors (two different plots, one for absolute error, one for relative error)related to the difference between the Taylor series
and f (x) over the interval (1 − 10−6 , 1 + 10−6 ). Make sure you use the Matllab abs function to obtain the absolute value of the error. Use a log scale on the y−axis.
(c) To identify the source of the errors plotted in (b) it is useful to compare to a reasonable bound for the truncation error expected for the Taylor series. Come up with a such a bound and plot its magnitude on the same log-linear plot from (b). You should have a different bound for x < 1 and x > 1 (you can first look at the simpler case of log(x) to understand why this happens). For x > 1 you can use the result mentioned in class for error of an alternating series. The case x < 1 is much harder. You should consider what dominates f(x) as x → 0+. (d) Consider the results from (c). From this you should be able to conclude that the problem is roundoff error rather than truncation error. Why? Explain what is making the roundoff errors so large and give an argument as to whether the Taylor series or the directly computed function is more accurate. Problem 4 In this problem we want to create a matlab function that can evaluate f(x) to a given accuracy for any value of x. (a) Create a new m-File, called myfofx.m. Unlike our previous script files, we would like this to be a function, just like log(x) or sin(x) that returns a number. i.e. we would like to be able to use the function in commands like: or To do this, we need to put the line >> y=myfofx(1.001)
>> plot(x,myfofx(x))
function [fx]=myfofx(x)
2

as the first non-commented line in the m-file. Then, fx will be the variable that we will use in the m-file that, at the end of the calculation, contains our answer. Note that unlike previous cases where x and T were scalars you will not need to set the value of x as it will be passed to the function. In this case, just return the value of the n = 8 Taylor series (i.e. replace the fprintf statement with fx=T before the return). Test the function by evaluating the result on the command line for myfofx(1) and myfofx(2). Make sure you are getting the correct result before proceeding.
(b) If we are close to x = 1 our previous results suggest that it would be better to use the Taylor series. However, if we are far away from x = 1, the accuracy of our Taylor series starts to degrade due to truncation error. Use an if-else construct to modify your function to use the Taylor series when 1 − 10−6 < x < 1 + 10−6 and the explicit expression for f (x) outside of this range. If you are unsure of how to use the if-else construct described in the matlab tutorial, look it up in the matlab help. In particular, the examples given there often very helpful. Other matlab functions and statements that may, or may not, be useful is the absolute value function abs and the OR statement. (c) Demonstrate that your function works by plotting its result over the same ranges of x used in problems 2 and 3. Submission requirements A section on submission requirements will be added later, together with format requirements for your lab. 3

程序代写代做代考 algorithm matlab Department of Engineering/Informatics, King’s College London Nature-Inspired Learning Algorithms (7CCSMBIM)

Department of Engineering/Informatics, King’s College London Nature-Inspired Learning Algorithms (7CCSMBIM)
Assignment 1
This coursework is assessed. A type-written report needs to be submitted online through KEATS by the deadline specified on the module’s KEATS webpage.
Q1 Binary Genetic Algorithm by Hand
a) Write down the first 7 digits of your student ID as s1s2s3s4s5s6s7. Form an 8-digit number as s2s3s4s5s6s7b1b2 where the two digits b1b2 denote your day of birth. (5 Marks)
b) Write down the cost function with two variables: f(x,y) = −(s2 +s3)x2 +
(s4 + s5)xy − (s6 + s7)y2 − (b1 + b2). In the following, we are going to find the
optimal solution for the optimisation problem: min f (x, y) using binary genetic x,y
algorithm.
(5 Marks)
c) Population Initialisation: Create a population with 8 chromosomes and list them in a table with the headings of ‘n’, ‘Chromosome’, ‘Decoded x, y’ and ‘Cost’ where n denotes the chromosome number. It is assumed that both variables x and y are in the range of −(s1 +s2) and s+s6 +s7 where s de- notes the largest digit among {s1, s2, s3, s4, s5, s6, s7}. The 8 chromosomes are [s2, s3], [s4, s5], [s6, s7], [b1, b2], [s3, s2], [s5, s4], [s7, s6], [b2, b1] where the first and the second digits represent x and y, respectively. 5-bit binary representation is employed for each digit resulting in 10-bit binary number for each chromosome.
(10 Marks)
d) Natural Selection: Show the ranked population after the process of Natural Selection with Nkeep = 4 in a table with the heading of ‘n’, ‘Chromosome’, ‘Decoded x, y’ and ‘Cost’. (10 Marks)
e) Selection: Using the cost weighting technique, show the probability table with the heading of ‘n’, ‘Chromosome’, ‘Decoded x, y’, ‘Cost’, ‘Cn = cn − cNkeep+1 ’,
n
‘Pn’ and ‘􏰄 Pn’. (10 Marks)
i=1
f) Crossover: Show the population after the process of Single-Point Crossover.
The chromosomes are selected for crossover according to the probability table
in the Selection process. The first pair of parents are chosen according to the
random numbers { s2 , 1 − s2 }. The next pair of parents s2 +s3 +s4 +s5 +s6 s2 +s3 +s4 +s5 +s6
are the rest two chromosomes in the pool of Nkeep. If the remaining number
of chromosomes is more than two. Make a remark and randomly pick two as
the second pair of parents. The crossover point for the first pair of parents is
right after the round(s2+s3 )th bit and the crossover point for the second pair 2
of parents is right after the round(s4+s5 )th bit, where the operator round(·) 2
1

rounds off the value to the nearest integer. Different colours should be used to show clearly where each part of the chromosome goes to in the crossover process. Note: The left most bit of the chromosome is the first bit. (10 Marks)
g) Mutation: Show the population in a table with the heading of ‘n’, ‘Chromo- some’, ‘Chromosome after mutation’, ‘Decoded x, y’ and ‘Cost’. The mutation rate is μ = 0.25. Calculate the number of bits to be mutated (#mutation) and randomly choose #mutation bits of your choice. Highlight the mutated bits.
(10 Marks) Q2 Denote R1 as the remainder of s2+s3+s4 . Write a Matlab script to find the minimum
9
of the function R1 + 1 in Appendix using binary genetic algorithm. All variables are
in the range of −20 and 20. The precision of the solution should be up to 4 decimal places.
a) Show your calculation getting R1. (5 Marks)
b) Determine the number of bits for each variable for binary decoding. Explain
your answer. (5 Marks)
c) Run the procedure of binary genetic algorithm for 10 times with the combi- nations of population size (p or Npop): 10, 50 100 and μ : 0.1, 0.5, 0.9. 9 combinations in total. Obtain the best the worst costs of the 10 runs for each combination; the mean and the standard deviation of the best the worst costs for the 10 runs for each combination. Specify other control parameters of binary genetic algorithm used in this question, e.g., number of iterations, population size, Nkeep, methods of crossover and mutation, etc. List the results in Table 1 and Table 2. (20 Marks)
d) Comment briefly on the results obtained (with support/evidence) in terms of reliability and sensitivity of the binary genetic algorithm. (10 Marks)
2

“Runs” Number
p = 10 μ = 0.1
p = 10 μ = 0.5
p = 10 μ = 0.9
p = 50 μ = 0.1
p = 50 μ = 0.5
p = 50 μ = 0.9
p = 100 μ = 0.1
p = 100 μ = 0.5
p = 100 μ = 0.9
1
2
3
4
5
6
7
8
9
10
Mean
Standard Deviation
Best Cost
Worst Cost
Table 1: Statistics of 10 runs.
Mean of “Mean”
Standard deviation of “mean”
Mean of “Standard Deviation”
Standard deviation of “Standard Deviation”
Mean of “Best Cost”
Standard deviation of “Best Cost”
Mean of “Worst Cost”
Standard deviation of “Worst Cost”
N = 2 + s2 + s3 N
F1: 􏰄 􏰀|xi| + cos(xi)􏰁 i=1
N
F2: 􏰄 􏰀|xi| + sin(xi)􏰁
i=1 N
F3: 􏰄x2i i=1
N−1
F4: 􏰄 􏰂100(xi+1 − x2i )2 + (1 + xi)2􏰃
i=1
Table 2: Overall Statistic.
Appendix 1: Test Functions
3

N
F5: 10N + 􏰄(x2i − 10 cos(2πxi))
i=1
􏰄N x2i 􏰅N
F6: 1 + 4000 − cos(xi) i=1 i=1
sin2 􏰂􏰆x2 + x2􏰃 − 0.5 12
F7: 0.5 +
F8: (x21 + x2)0.25 sin 􏰀30((x1 + 0.5)2 + x2)0.1􏰁 + |x1| + |x2|
F9: −x1 sin􏰂􏰆|x1 −(x2 +9)|􏰃−(x2 +9)sin􏰂􏰆|0.5×1 +x2 +9|􏰃
In the above test functions, all xi, i = 1, 2, · · · , N, are decision variables.
Marking: The learning outcomes of this assignment are that students will understand the fundamental principle of binary genetic algorithm (BGA) and appreciate the BGA performance through the evaluation of some benchmark functions. The assessment will look into the knowledge and understanding on the topics. When answering the questions, show/explain/describe clearly the steps with reference to the equations/theory/algorithms (stated in the lecture slides). When making comments, provide statements with support from the results obtained.
Purposes of Assignment: This assignment is designed to reinforce the understand- ing of Genetic Algorithm by going through every single step and to get an idea how it performs when applying the Genetic Algorithm to solve a numerical problem. After do- ing this assignment, students should be aware of the capability and limitations of Genetic Algorithm and thus know what to note when applying it.
1 + 0.1(x21 + x2)
4

程序代写代做代考 Excel Advanced Research Methods 2020: A guide to R-studio

Advanced Research Methods 2020: A guide to R-studio

Tests of association:
IV qualitative, DV quantitative
Tests of correlation:
IV & DV quantitative
Cause-consequence relationship:
IV & DV quantitative
IV & DV qualitative

Parametric
Non parametric 
Parametric 
Non parametric

2 variables
T-test
Mann-Whitley-U
Wilcox 
Cor test
Spearman test
Regression
Chi-square
Fisher’s test
3+ variables
Anova
Kruskal


 IMPORTING DATA

From excel:

Upper right hand quadrant


Environment → import data set → from Excel


When using formulas, identify your variables as (file-name$column-name)

By hand: 
>variable1<-c(#,#,#,#,#,#) >variable2<-c(#,#,#,#,#,#) •  TESTING TWO VARIABLES FOR ASSOCIATION • •  Run the Shapiro test for normal distribution on each variable: • > shapiro.test(variable1)
> shapiro.test(variable2)
If p-value>0.05 for both variables, there is no significant difference between their distribution and the normal perfect curve. Proceed to variance test in 2.2. 

If p-value<0.05 for either variable, there is a significant difference between its distribution and the normal perfect curve. The data is not parametric, so the T-test cannot be run. Proceed to Mann-Whitley-U or Wilcox test instead. See 2.4.  • Run the variance test on both variables to check for equality of variances. Equality of variances means that the average distance of all results versus the mean are not different when we compare them.  • >var.test(variable1,variable2)

If p-value>0.05, the ratios are equal and there is equality of variances. The data is parametric. Proceed to T-test in 2.3.

If p-value<0.05, the ratios are not equal and there is no equality of variances. The data is not parametric. Proceed to Mann-Whitley-U or Wilcox test. See 2.4. •  If the data is parametric as shown in the shapiro and variance tests, run the T-test. • REGULAR T-TEST  >t.test(variable1,variable2) 

OR MATCHED T-TEST for paired data (when the same subject is tested twice, before and after some intervention)

>t.test(before,after,paired=TRUE) 

If p-value>0.05, the association is not significant. You may need more data.

If p-value<0.05, the association is significant. Yay!  When p-value = ...e-X, X is the number of zeros which precede the given number. It’s very significant.  •  If the data is NOT parametric as shown in the shapiro and variance tests, run the Wilcox test. The Mann-Whitley-U test is another option, but we didn’t go over it in class.  • FOR REGULAR DATA  >wilcox.test(variable1,variable2,paired=F)
(F=false)

FOR PAIRED DATA
>wilcox.test(variable1,variable2,paired=TRUE)


TESTING THREE OR MORE VARIABLES FOR ASSOCIATION


First reformat your data into two columns in Excel. You will need to import both the original (storage) version and the reformatted version into R-studio. 

STORAGE VERSION:

Number of words
Spain
UK
Russia
112
152
178
143
161
167
143
144
181

REFORMATTED VERSION:

No words
Nationality
112
Spain
143
Spain
143
Spain
152
UK
161
UK
144
UK
178
Russia
167
Russia
181
Russia


Run the Shapiro test with the original/storage version of the data to check for normal distribution:

>shapiro.test(independent-variable1)
>shapiro.test(independent-variable2)
>shapiro.test(independent-variable3)

For example:
>shapiro.test(N_words$Spain)
>shapiro.test(N_words$UK)
>shapiro.test(N_words$Russia)

If p-value>0.05 for all variables, there is no significant difference between their distribution and the normal perfect curve. Proceed to Bartlett test in 3.3.

If p-value<0.05 for any variable, there is a significant difference between its distribution and the normal perfect curve. The data is not parametric, so the Anova test cannot be run. Proceed to Kruskal test in 3.5.   • Run the Bartlett test with the reformatted version of the data to check for equality of variances: • >bartlett.test(dependent-variable~independent-variable)

For example:
>bartlett.test(N_words_2$No words~N_words_2$Nationality)

If p-value>0.05, the ratios are equal and there is equality of variances. The data is parametric. Proceed to Anova test in 3.4.

If p-value<0.05, the ratios are not equal and there is no equality of variances. The data is not parametric. Proceed to Kruskal test in 3.5. • Run the Anova test with the reformatted version of the data to check for statistical significance of parametric data: • >name1<-lm(dependent-variable~independent-variable)* >anova(name1)

For example:
>Res_anova<-lm(N_words_2$No words~N_words_2$Nationality) >anova(res_anova)

*Note: lm stands for “linear model”

When reporting data, we state: “The anova test gave the F value … , … degrees of freedom, and the result Pr(>F)* …”

*Pr(>F) is the significance level. It is signaled with asterisks at the bottom of the results of the Anova test.

If you wish to do post-hoc tests, you may choose to do an analysis of variables instead of the linear model:
>name2<-aov(dependent-variable~independent-variable) >anova(name2)
>name2
>summary(name2)

For example: 
>Res_anova2<-aov(N_words_2$No words~N_words_2$Nationality) >anova(Res_anova2)
>Res_anova2
>summary(Res_anova2)

The Tukey HSD post-hoc test shows the differences between each group. It tells us which of the groups are more salient and which are related to one another. 
>TukeyHSD(name2)

For example:
>TukeyHSD(Res_anova2)


Run the Kruskal test with the reformatted version of the data to check for statistical significance of non parametric data:

>kruskal.test(dependent-variable~independent-variable)

For example:
>kruskal.test(schools$mistakes~schools$school)

If p-value>0.05, the association is not significant.  You may need more data.

If p-value<0.05, the association is significant.  Yay!  • TESTING TWO VARIABLES FOR CORRELATION • Tests for correlation are often used in social sciences. They make no cause-effect assumption because we use them when no experiment or intervention has taken place. We simply select two variables and run tests to see if there is a relationship between the two (e.g. length of study abroad and language level). There is no control group or expected direct influence. • First import your dataset to R-studio, check out its structure and other basic information: • >str(Filename)
>name3<-(data.frame=Filename)* >name3**

*Nothing should happen here. If you don’t capitalize properly, you’ll get an error message.
**This will produce a table.

For example:
>str(Stay)
>relevance.stay<-(data.frame=Stay) >relevance.stay


Now run the Shapiro test to check for normal distribution. 

>shapiro.test(variable1)
>shapiro.test(variable2)

For example:
>shapiro.test(Stay$length_of_stay)
>shapiro.test(Stay$marks)

If p-value>0.05 for both variables, there is no significant difference between their distribution and the normal perfect curve. The data is parametric. Proceed to cor test in 4.3.

If p-value<0.05 for either variable, there is a significant difference between its distribution and the normal perfect curve. The data is not parametric, so the cor test cannot be run. Proceed to Spearman test in 4.4. • If the data is parametric, run the cor test. • >cor.test(variable1,variable2)

For example:
>cor.test(Stay$length_of_stay,Stay$marks)

The cor result must be >0.7 to be significant. 

4.4.  If the data is not parametric, run the Spearman test.
>cor.test(~name3$variable1 + name3$variable2,data=name3,method=”spearman”,continuity=”FALSE”,conf.level=0.95)*
*The “name” will depend on how you named the data in 4.1. 

For example:
>relation<-data.frame(metaphors_adjectives)** >relation
>shapiro.test(Metaphors_adjectives$metaphor)
>shapiro.test(Metaphors_adjectives$adjective)
>cor.test(~relation$Metaphor + relation$Adjective,data=relation,method=”spearman”,continuity=”FALSE”,conf.level=0.95)

The RHO result must be >0.7 to be significant.

**This is the naming process from 4.1.


TESTING VARIABLES FOR A CAUSE-CONSEQUENCE RELATIONSHIP

To test variables for a cause-consequence relationship, we use regression. 
>str(filename)
>name4=lm(variable1~variable2)
>name4$coefficients
>name4$residuals
>lm(formula=variable1~variable2)
>summary(name4)

For example:
>str(corpus_regr)
>modelX=lm(corpus_regr$X~corpus_regr$Y)
>modelX$coefficients
>modelX$residuals
>lm(formula=corpus_regr$X~corpus_regr$Y)
>summary(modelX)

Report on adjusted R-squared number and p-value (Pr(>|t|), second row). The significance is signaled with asterisks at the bottom of the table generated by the summary. 


QUALITATIVE DATA: ASSESSING SIGNIFICANCE

When both the independent and dependent variables are qualitative, we devise a contingency table, in which each element can only occupy one cell. The numbers in each cell represent the number of cases (instances) of the given combination of  variables.

This is one of the most frequent tests in linguistics because we normally analyze data in categories.

Turn

Beginning 
Middle
End
Yes
13
2
1
No
2
13
14

To calculate significance, we can enter our data into the online calculator on Quantspy.org and run the Chi Square test, as long as:

No cell has 0 cases


Each cell has at least 5 cases

If any cell has less than 5 cases, we can run as Fisher’s test, as in this example from class:

China
Spain
US
Canada
Iran
Slovenia
Male
0
2
0
1
0
0
Female
3
2
1
0
1
1


GRAPHING YOUR DATA


Graph the number of cases of individual variables in a histogram.

>hist(variable1,breaks=13,density=8,angle=45,col=“color-name”,main=“title-of-histogram”,xlab= “x-axis-label”,ylab=“y-axis-label”)
>hist(variable2,breaks=13,density=8,angle=45,col=“color-name”,main=“title-of-histogram”,xlab= “x-axis-label”,ylab=“y-axis-label”)
Breaks: Intervals (number of bars, groups) into which the data is divided to gauge frequency
Density: Shading of the bars
Angle: Degree of the angle of the lines used to shade the bars
Col: Color of the shading
Main: Title of the histogram
Xlab: X-axis label
Ylab: Y-axis label


Graph the independent variable against the dependent variable in a box plot.

>boxplot(variable1,variable2,ylab= “y-axis-label”,main=“title-of-boxplot”, col=“color-name”, names=c(“name-of-variable1”,“name-of-variable2”))

程序代写代做代考 1007ICT / 1807ICT / 7611ICT Computer Systems & Networks

1007ICT / 1807ICT / 7611ICT Computer Systems & Networks
3C. Digital Logic and Digital Circuits
Dr. Sven Venema Dr. Vallipuram Muthukkumarasamy

Last Lecture:
Topics Covered:
• Logic unit, Selection logic, Decoder logic
• Multiplexing and Demultiplexing
• Half and Full adders

Lecture Content
 Learningobjectives
 Arithmeticlogicunit
 Binarymultiplicationanddivision
 Shifting
 SequentialLogic
 Datalatches,S-RLatch
 Clocksandsynchronisation
 Registers,Buses,Computermemory
© Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan
Page 3

Learning Objectives
At the end of this lecture you will have gained an understanding of:
 Arithmetic logic unit
 Binary multiplication and division
 Shifting
 Sequential Logic
 Data latches, S-R Latch
 Clocks and synchronisation
 Registers, Buses, Computer memory
© Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan
Page 4

ALU – Arithmetic Logic Unit (Section 7.2)
 The ALU is a general processing element
 It puts everything we have learnt together
 ALUs are combined in parallel for multi-bit versions
AB
AND
OR
XOR
Select Cin Cout
1 bit ALU
Select
Cout
A2 B2 A1
ALU ALU
B1 A0 B0
ALU
Cin
Full Adder
Output
3 bit ALU
© Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan
Page 5
Output

Multiplication and Division By 2
To multiply by 2 in binary, shift bits left and insert a zero at the right hand side.

Carry out
0

To divide by 2 in binary, shift bits right and insert a zero at the left hand side.
0 Carry out
(ignored)
© Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan
Page 6
00012 = 110 00102 = 210 01002 = 410
01112 = 710 00112 = 310 00012 = 110

Shifters
 Wecanusemultiplexorstoshiftbitsleftandright.
 Weneedtoselecteachoutputbittobetheinputbit
on its left or right side
Inputs
D4
D3
D2
D1
D0
Shift Left
Outputs
X3
X3
X2
X1
X0
Inputs
D4
D3
D2
D1
D0
Shift Right
Outputs
X3
X3
X2
X1
X0
Sign or 0 Left / Right
4 bit shifter
D3 D2 D1 D0
0
X3 X2 X1 X0
© Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan
Page 7

Shifters
What if we also want the shifter to not shift or to set the output to zero? Use a 4-input multiplexor
D3 D2 D1 D0
SEL
Out
00
Zero
01
Right
10
Left
11
Thru

TLRZ TLRZ TLRZ TLRZ
Sign or 0 SEL
0
X3 X2 X1 X0
Page 8
© Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan

Arbitrary Multiplication
 TomultiplybyothernumberssayA*B–wecouldaddAto itself B times, but it’s faster to use shifts and adds like this…
 The powers of 2 you need to add to get the multiplicand determines the number combination of shifts and addition we need to perform on the multiplier (ie the 1s in its binary value)
 Let << denote the binary left shift operator:  10x5=(10x4)+(10x1)=1100102 Mult. Shifts Binary Hex 10 x 4 10 x 1 1010 << 2 1010 << 0 101000 001010 28 0A 5 = 1012 = 1002 + 12 =4+1  10x7=(10x4)+(10x2)+(10x1)=10001102 Mult. Shifts Binary Hex 10 x 4 10 x 2 10 x 1 1010 << 2 1010 << 1 1010 << 0 101000 010100 001010 28 14 0A 7 = 1112 =1002 +102 +12 =4+2+1 © Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan Page 9 Multiplication Example Multiply SumA x B  Check every bit position of B so that if:  bitposition0ofBis1,addAtothesum.  bitposition1ofBis1,addA<<1tothesum.  bitposition2ofBis1,addA<<2tothesum.  bitposition3ofBis1,addA<<3tothesum.  etc.. 10 × 13 = 130 10102 x 11012 Note: 10102 << 1 is not added as bit position 1 of 11012 is 0. 10102 <<0 10102 <<2 10102 <<3 10102 1010002 + 10100002 + 100000102 = 130 © Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan Page 10 Arbitrary Division  Forarbitrarydivisionwecanusebasicbinarylong division. 84 21 2 1 13 / 3 = 1 1 0 1 / 1 1 = 4 Remainder 1 1 0 0 Answer: 4 1 1 1 1 01 -1 1 0 0 1 Remainder: 1 © Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan Page 11 Sequential Logic (Section 2.5) Previously we looked at which produces an output as some combination of the input values. Sequential logic produces an output that depends not only on the inputs but on previous inputs as well.  combinatorial logic  Input Output Logic Function © Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan Page 12 Feedback Memory Cell Data Latches  Noneofthelogicfunctionswesawbeforecanstore any data... bits come in and go straight out again. A  Considerthefollowinglogic: Latch is a logic function that can store bits in  Thiscanstorea‘1’bitbutnota‘0’bit.Weneed another input to tell it to store a ‘0’bit, like this. Q OR set reset OR Q © Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan Page 13 S-R Latch (RS-Bistable)  Let’srearrangethelogicabitasfollowsusingthe rules of logic (using DeMorgan’s Theorem) : SQSQ RR  TheresultiscalledtheSR-latch(orRS-Bistable)  BothinputsarenormallyOFF(at0)  TheSinputsetsthedatastateto1  TheRinputsetsthedatastateto0  HavingbothtoONatonceisillegal  WhenbothareOFFthelatchisstable  EitherQ=0andQ=1  Or Q=1andQ=0 S Q R Q © Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan Page 14 Clocks and Synchronisation  Themainproblemwithlatchesisthataftertheinputs change the output is unstable for a short time.  Ifwedirectlyconnecttheoutputofalatchtotheinput of another circuit then the circuit may be unstable  Aclocksignalcancontrolwhenalatchcanloadits inputs after they are stable (ie when the clock is high) Q Q 10 S Clk 10 10 R  Clockedlatchesaresometimescalled  Thefastertheclock–thefasterthatdatacanbe stored/read into a latch © Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan Page 15 Flip Flops; - Data Latch (Level-Triggered D-Type bistable)  WecanuseDeMorgan’sTheoremagaintoconvertthe Latch to use NAND gates that is set using OFF inputs.  BothinputsarenormallyON  SettingStoOFFsetsthedatastateto1  SettingRtoOFFsetsthedatastateto0  HavingbothtoOFFatonceisillegal S R - Q Q Q Q  WhenbothareONthelatchis  Asimplemodificationoftheclockedversionletsus stable create the useful D D FlipFlop Latch or D Clk - Symbol DQ © Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan Page 16 Bits / Bytes / Words  Ifcomputermemorywasonlyaddressedonebitata time, it would take quite a long time to retrieve enough data to any serious processing.  Mostcomputersdonotprocessindividualbitsbut instead group them together into multiples of 8 eg 8, 16, 32, 64 etc.  Thesegroupsaredescribedas length varies depending on the machine.  An8bitwordiscalleda words, but word Byte. Nibble so 1 byte = 2 nibbles  A4bitwordiscalleda  Therearenospecialnamesforothersizedwords. © Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan Page 17 Registers Data Latches (Level-Triggered D-Type bistables) allow us to store 1 bit of information but we can group them in parallel   This is called a of multiple bits. register to store data consisting wordsize is the number of bits a register  The can store Clk D3 D2 D1 D0 Q3 Q2 Q1 Q0 Simple 4 bit register using D-Latches D Q D Q D Q D Q 7 6 5 4 3 2 1 0 © Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan Page 18 8 bit register Buses  Wecanconnectlogicgatestogetherwithlinesthat convey single bits of information between them.  Withregisterswehavemultipleinputandoutput lines to convey N-bits of data to and from the register  Abusisasetoflinesthatsimultaneouslyconveysa set of bits between components.  Twotypesofbusesarecommonincomputer systems: point-to-point, and multipoint buses. Register A Point to Point Bus Shared Bus (Multipoint) Register B © Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan Page 19 Reg A ALU Reg B Multipoint Buses use special gates with “tristate” outputs that can be connected together Computer Memory (Section 3.3)  Wecanuseanarrayofregistersinseriestocreate a memory bank.  Everyregisterlocationinthememorybankisgiven a unique address that is used so that we can select it and access the data stored in it.  An8bitmachinewoulduseabankof8bitregisters and access 8 bit words from memory at a time. Location Bit 43 7 0 6 5 0 0 2 0 0 1 1 0 1 0 1 1 0 0 0 0 1 0 0 1 1 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 005 Fetching word at address 003 004 would return the value 011001002 = 6416 = 10010 003 002 001 000 © Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan Page 20 Computer Memory  A memory bank needs some way of selecting memory addresses  A special register called a memory address register ( is internal to the CPU contains the physical location of the next memory address that will be selected for reading/writing.  Another internal register called the Memory Buffer Register ( MAR) which MBR) MDR)] holds the value that was read [or Memory Data Register ( /written to the selected memory address. Location Bit 7 0 6 5 0 0 2 0 0 1 1 0 1 0 1 1 0 0 0 0 1 0 0 1 1 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 Read/Write control 005 004 003 002 001 000 43 0 0 1 1 0 1 1 0 0 1 0 0 MAR MBR (MDR) © Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan Page 21 Summary Have considered:  Arithmetic logic unit  Binary multiplication and division  Shifting  Sequential Logic  Data latches, S-R Latch  Clocks and synchronisation  Registers, Buses, Computer memory © Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan Page 22 Next....  Processors © Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan Page 23

程序代写代做代考 1007ICT / 1807ICT / 7611ICT Computer Systems & Networks

1007ICT / 1807ICT / 7611ICT Computer Systems & Networks
3B. Digital Logic and Digital Circuits
Dr. Sven Venema Dr. Vallipuram Muthukkumarasamy

Last Lecture:
Topics Covered:
• Digital logic, Basic logic gates, Boolean algebra
• Combinatorial logic gates

Lecture Content
 Learning objectives
 Logic unit, Selection logic, Decoder logic  Multiplexing and demultiplexing
 Half and Full adders
© Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan
Page 3

Learning Objectives
At the end of this lecture you will have gained an understanding of:
 Selection logic
 Decoder logic
 Multiplexors
 Demultiplexors
 Half and Full adders
© Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan
Page 4

Logic Unit
Lets try to create a “programmable” logic unit that permits us to apply a predefined logic function to a given set of inputs.
ab
Output Select
We need a function that lets us select what operation to perform

AND OR XOR
NOT

© Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan
Page 5

Selection Logic
 Saywehaveanumberofinputs‘A,B,C,D’andwe want to select one of them to use in a logic function.
 Weneedaspecialfunctiontoswitchtheselected input into the output ‘X’ based on the selection.
 WecanuseinputsS0toS3toselectbetweenA-D
A B C D
Selector
X
S0 S1 S2 S3
© Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan
Page 6

Decoder Logic
 Justsaywewanttoselectbetweenoneof100’s of possible inputs – we need 100’s of selection inputs as well which gets too complicated.
 DecoderswithNinputsallowustoenableany one of 2N possible selection lines.
 Basicallyadecodertakesabinarycodednumber and enables the output representing the number
Inputs
Outputs
s1
s2
x0
x1
x2
x3
0
0
1
0
0
0
0
1
0
1
0
0
1
0
0
0
1
0
1
1
0
0
0
1
2 to 4 Decoder
x0 = s1ANDs2 x1 = s1ANDs2 x2 = s1ANDs2 x3 = s1ANDs2
X0 X1
X2 X3
2N outputs
© Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan
Page 7
S2 S1
N Inputs

Multiplexing
 Combiningtheselectoranddecoderwecan
create what is called a
 IngeneralifwehaveNinputswewanttoswitch between we need to have log2(N) selection lines.
Multiplexor
A B C D
X
s0
s1
X
0
0
A
0
1
B
1
0
C
1
1
D
Decoder
S0 S1 selection
© Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan
Page 8
2N inputs

Demultiplexing
We can also switch in the opposite direction to send one input ‘A’ into one of many different outputs (eg X1..Xn)

Decoder
A
X1 X2
Input X1 A X2
outputs X4
X3 X3
X4
(s0,s1) Select
S0 S1 selection
© Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan
Page 9

Half-Adders
In addition to logic functions we can also create maths functions.
The simplest math function is the half-adder which can add 2 digits (bits) to give a sum and a carry bit
0011A 0 1 0 1B+ 0 1 1 10
AB


A
B
Sum
C
0
0
0
0
0
1
1
0
1
0
1
0
1
1
0
1
Sum = A XOR B Carry = A AND B
© Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan
Page 10

Full-Adders
 Ifwewanttoaddmorethan1bitvaluestogether we need to deal with the carry.
 Full-addersacceptthetwoinputstobeaddedplus the carry from a previous stage.
 Thecircuitmustbeabletodealwithpropagation delays
00 00 01 01 00 10 11 11A 00 01 00 01 10 01 10 11B+ 00 01 01 10 10 11 101 110
A0 B0 A1 B1 A2 B2 A3 B3
Full Adder
Full Adder
Full Adder
Full Adder
Cin
Cout
Page 11
S0 S1 4 bit adder S2 S3 © Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan

Full-Adders
The logic to perform add with carry combines two half adders together.
Sum =AXORBXORCin
Cout = (AANDB)OR(CinAND(AXORB))

Cin
A
B
Sum
Cout
0
0
0
0
0
0
0
1
1
0
0
1
0
1
0
0
1
1
0
1
1
0
0
1
0
1
0
1
0
1
1
1
0
0
1
1
1
1
1
1
Cin AB
Sum Cout
Sum Carry
Sum A+B
© Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan
Page 12

Subtraction
 A–BisthesameasA+(-B)
 IfweconvertBtothenegativeequivalentofits value, we can use the basic adder as it is. We can use an XOR gate to do this.
 However,convertingBto–Busingtwo’s complement also requires adding 1
A B0 Sign bit 0
+0 if positive +1 if negative
© Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan
Page 13
Full Adder
S0

Summary
Have considered:  Selection logic  Decoder logic
 Multiplexors
 Demultiplexors
 Half and Full adders
© Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan
Page 14

Next….
 Arithmetic logic unit
 Binary multiplication and division
 Shifting
 Sequential Logic
 Data latches, S-R Latch
 Clocks and synchronisation
 Registers, Buses, Computer memory  Processors and Memory Organisation
© Ruben Gonzalez. Revised and updated by Sven Venema, Vallipuram Muthukkumarasamy, and Wee Lum Tan
Page 15